python - 选择列表/列/数组的每个第 n 个子集

标签 python

如何从以下元素列表中按索引进行选择,即索引 1,2,然后是 5,6,然后是 9,10? 数字和文字不相关,顺序相关。背后的基本思想如下:假设您有特征 a、b、c、d,并且对于所有这些特征,您都有平均值、标准差、最小值和最大值。如果您只对显示功能 b 和 c 感兴趣,如何显示它们?

column=[]
for i in range(1,4):
    for j in list('abcd'):
        column.append(str(j)+str(i))
 column
['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2', 'a3', 'b3', 'c3', 'd3']

如何提取索引 1、2、5、6、9、10 处的值,结果为

['b1', 'c1', 'b2', 'c2', 'b3', 'c3']

最佳答案

一种方法是使用itertools.compressitertools.cycle 。它基本上使用掩码为每个 4 元素 block 重复选择索引 1 和 2 处的元素。

import itertools as it

print([x for x in it.compress(column, it.cycle([0, 1, 1, 0]))])
# ['b1', 'c1', 'b2', 'c2', 'b3', 'c3']

关于python - 选择列表/列/数组的每个第 n 个子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049560/

相关文章:

python - '#!/usr/bin/python' 在每个 Python 脚本前面是必须的吗?

python - 创建对象集合的最有效方法?

python - 如何在 Python 中找到带有字符串列表的预先存在的变量?

python - 在 python 中访问 HIDAPI 库

python - 无法点击不同结果从内页解析标题

python - 更改 Altair 图例中的形状颜色

python - Django-rest-framework中的可写嵌套序列化器?

python - python 中的 Unicode 错误与表单(使用 Mechanize)

python - 在存储在谷歌驱动器中的谷歌 Colaboratory 中导入 zip 文件

python - 如何从 Sphinx 的默认搜索中排除 RST 文件?