python动态创建循环

标签 python python-3.x

我有一个名为 table 的二维矩阵和一个名为 count 的列表。在表中,数据存储在计算每列中数据集的数量中。 first_index 只显示组合的数量,在这种情况下有 588 种组合 (7*6*2*7) 现在我想创建一个任意到任意的关系。我的代码是静态的,所以我需要创建动态循环/变量的可能性。

表格:

[1, 30, 50, 60]
[2, 31, 51, 61]
[3, 32, 0, 62]
[4, 33, 0, 63]
[5, 34, 0, 64]
[6, 35, 0, 65]
[7, 0, 0, 66]

计数:

[7, 6, 2, 7]

代码在我的例子中工作正常,但不确定是否有超过 4 行,所以它不是很好的代码。我是 python 菜鸟,也许有另一种方法可以解决这个问题

for k in range(count[0]):
    for kk in range(count[1]):
        for kkk in range(count[2]):
            for kkkk in range(count[3]):
                print('{0:3} , {1:3} , {2:1}'.format(first_index, table[k][0], 1))
                print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[kk][1], 2))
                print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[kkk][2], 3))
                print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[kkkk][3], 4))
                print
                first_index+=1

输出看起来像

1 ,   1 , 1
1 ,  30 , 2
1 ,  50 , 3
1 ,  60 , 4

2 ,   1 , 1
2 ,  30 , 2
2 ,  50 , 3
2 ,  61 , 4

...

588 ,   7 , 1
588 ,  35 , 2
588 ,  51 , 3
588 ,  66 , 4

最佳答案

这里使用的是 itertools.product但使用巧妙的逻辑。

from itertools import product

def special_combinations(table):
    for r in product(*zip(*table)):
        if 0 in r:
            continue
        yield r

您根本不需要 count 变量。使用此解决方案:

>>> table = [[1, 30, 50, 60],
             [2, 31, 51, 61],
             [3, 32,  0, 62],
             [4, 33,  0, 63],
             [5, 34,  0, 64],
             [6, 35,  0, 65],
             [7,  0,  0, 66]]
>>> for idx, val in enumerate(special_combinations(table)):
    print idx+1, val

1 (1, 30, 50, 60)
2 (1, 30, 50, 61)
3 (1, 30, 50, 62)
4 (1, 30, 50, 63)
5 (1, 30, 50, 64)
6 (1, 30, 50, 65)
7 (1, 30, 50, 66)
8 (1, 30, 51, 60)
9 (1, 30, 51, 61)
10 (1, 30, 51, 62)
...
584 (7, 35, 51, 62)
585 (7, 35, 51, 63)
586 (7, 35, 51, 64)
587 (7, 35, 51, 65)
588 (7, 35, 51, 66)

奖励:单行:

[(i+1, R) for i, R in enumerate(r for r in product(*zip(*table)) if not 0 in r)]

注意:如果您从表格中删除零,您可以获得更好的性能。

>>> table
[[1, 30, 50, 60], 
[2, 31, 51, 61], 
[3, 32, 0, 62], 
[4, 33, 0, 63], 
[5, 34, 0, 64], 
[6, 35, 0, 65], 
[7, 0, 0, 66]]
>>> table = [t[:t.index(0)] if 0 in t else t for t in map(list, zip(*table))]
>>> table
[[1, 2, 3, 4, 5, 6, 7], 
[30, 31, 32, 33, 34, 35], 
[50, 51], 
[60, 61, 62, 63, 64, 65, 66]]

然后您的解决方案就简单多了。

>>> [(i+1, R) for i, R in enumerate(r for r in product(*table))]

关于python动态创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357469/

相关文章:

python - 检查函数是否被调用为装饰器

python - Django 刷新数据库直到事务结束

python - 将数组的数组除以标量数组

python - 如果存在特定模式(例如数字然后字母),如何将数据透视表应用于数据框列?

python - 只有在重复而不是单词的一部分时才用另一个替换字符

python - Pandas 系列中的特殊字符串格式

python - 将标签的文本更改为 json 文件中的值,但是当我运行程序时,标签为空白

python - 防止多处理库中的文件句柄继承

python - 从 docker 发送 ddtrace

python-3.x - Biopython 记录基因两侧的额外 2 个核苷酸,用于 +2,-2 阅读框