遍历3个列表的更好方法

时间:2018-10-14 16:45:09

标签: python

我正在创建一个程序,该程序在图像的宽度和高度上进行迭代,并使用一组键。

这里是一个例子:

width = [0,1,2,3,4,6,7,8,9]
height = [0,1,2,3,4]
keys = [18,20,11]

宽度和高度是一个整数范围,最大为宽度和高度的大小。 键是任何一组数字(实际上是ASCII值),但不是有序数字。

我希望输出如下:

0 0 18
0 1 20
0 2 11
0 3 18
0 4 20
1 0 11
1 1 18
. . ..
9 0 20
9 1 11
9 2 18
9 3 20
9 4 11

如您所见,宽度和高度可以通过嵌套的for循环来产生,而键则在彼此之间循环。

这是我的解决方法:

w = [0,1,2,3,4,6,7,8,9]
h = [0,1,2,3,4]
k = [18,20,11]

kIndex = 0

for i in w:
    for j in h:
        print(i,j,k[kIndex])
        # Cycle through the keys index.
        # The modulo is used to return to the beginning of the keys list
        kIndex = (kIndex + 1) % len(k)

实际上,它可以按预期工作,但是,我想要一种更有效的方法来执行上述操作,而不是在键列表的索引位置中使用增量变量。

如果要使用嵌套的for循环,我不介意,但是索引键变量让我很烦,因为如果没有它,代码似乎无法工作,但同时又不是真正的pythonic

3 个答案:

答案 0 :(得分:11)

您可以使用itertools.product来获得宽度和高度的乘积,即整个网格。然后,您想循环浏览键,因此使用itertools.cycle。您终于zip将它们在一起,并获得了预期的结果。

您可以使用yield使其成为生成器,以提高存储效率。

from itertools import product, cycle

def get_grid(width, height, keys):
    for pos, key in zip(product(width, height), cycle(keys)):
        yield (*pos, key)

或者如果您不需要发电机。

out = [(*pos, key) for pos, key in zip(product(width, height), cycle(keys))]

示例

width = [0,1,2,3,4,6,7,8,9]
height = [0,1,2,3,4]
keys = [18,20,11]

for triple in get_grid(width, height, keys):
    print(triple)

输出

(0, 0, 18)
(0, 1, 20)
(0, 2, 11)
(0, 3, 18)
(0, 4, 20)
(1, 0, 11)
(1, 1, 18)
...

请注意,您可以用范围替换定义widthheight的列表。

width = range(10)
height = range(5)

答案 1 :(得分:1)

您可以从itertools使用循环。

from itertools import cycle, product

width = [0,1,2,3,4,6,7,8,9]
height = [0,1,2,3,4]
keys = [18,20,11]


c = cycle(keys)

for w,h in product(width,height):
    print(w,h,next(c))

答案 2 :(得分:0)

您可以在矩阵上使用迭代。它的ndenumerate函数来自numpy数据包。如果width和height是int的范围,则可以跳过创建列表。只需定义此列表的大小即可。

width = 10
height = 5
k = [18,20,11]

kIndex = 0

for (i,j), value in np.ndenumerate(np.ones((height,width))):
    print(i,j,k[kIndex])
    # Cycle through the keys index.
    # The modulo is used to return to the beginning of the keys list
    kIndex = (kIndex + 1) % len(k)
相关问题