gpt4 book ai didi

python - 迭代 3 个列表的更好方法

转载 作者:太空狗 更新时间:2023-10-29 21:27:45 24 4
gpt4 key购买 nike

我正在创建一个程序,它遍历图像的宽度和高度并使用一组键。

这是一个例子:

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 .

最佳答案

您可以使用 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)

关于python - 迭代 3 个列表的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52804895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com