我用itertools在python中生成了一个二进制数列表,其中我想将所有1转换为'all',将所有0转换为attribs列表的索引,其中attribs列表是[1,2],度量值10附加在每个列表的末尾。
实际上,二进制数的列表是
[(0, 0), (0, 1), (1, 0), (1, 1)]
我想把它们转换成
[(1, 2), (1, 'ALL'), ('ALL', 2), ('ALL', 'ALL')]
所以这些将是列表[1,2]的一种组合形式。
打印时的最终列表应如下所示:
[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
不过,我现在得到的是:
[2, 2, 10]
[2, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
我做错什么了?
import itertools as it
measure = 10
attribs = [1, 2]
# generate binary table based on number of columns
outs = [i for i in it.product(range(2), repeat=(len(attribs)))]
print(outs)
for line in outs:
line = list(line)
# replace binary of 1 or 0 with 'ALL' or value from input
for index, item in enumerate(line):
print("index of line: " + str(index) + " with value: " + str(item))
if (item == 1):
line[index] = 'ALL'
elif (item == 0):
for i in range(len(attribs)):
print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
line[index] = attribs[i]
line.append(measure)
print(line)
最佳答案
在elif
部分中,循环将一直执行到将attribs[1]
分配给line[index]
的结尾,即2。
elif (item == 0):
for i in range(len(attribs)):
print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
line[index] = attribs[i]
相反,您需要跟踪0和1的索引,以便执行以下操作:
elif (item == 0):
print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
line[index] = attribs[bin_index]
但毕竟,作为一种更像蟒蛇的方式,您可以使用嵌套列表理解:
In [46]: [['ALL' if i else ind for ind, i in enumerate(items, 1)] + [10] for items in lst]
Out[46]: [[1, 2, 10], [1, 'ALL', 10], ['ALL', 2, 10], ['ALL', 'ALL', 10]]