python - 根据列表索引将二进制列表转换为组合所需的值

标签 python list loops binary python-itertools

我用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] 

但毕竟,作为一种更像 Python 的方式,您可以只使用嵌套列表理解:

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]]

关于python - 根据列表索引将二进制列表转换为组合所需的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43179609/

相关文章:

python - 从函数 **keywords 为 sql 语句创建字符串

python - 使用枚举从现有列表中生成第二个列表时跳过索引的问题

python - 如何制作一个 Python 程序来演示 Zipf 定律?

python - 搜索字典以获取每个键的完整路径

Python 属性错误 : 'numpy.ndarray'

python - Sklearn 变换错误 : Expected 2D array, 改为一维数组

python - Pandas groupby 将自定义功能应用于每个组

java - 如何获取arrayList的重复元素和非重复元素?

php - 比较数组并在相同顺序下压缩它

java - 如何检查输入是否为整数?