gpt4 book ai didi

python - 如何迭代列表的笛卡尔积

转载 作者:太空狗 更新时间:2023-10-29 20:36:06 25 4
gpt4 key购买 nike

我想使用 3 个(或任意数量的)包含任意数量元素的列表在 for 循环中进行迭代,例如:

from itertools import izip
for x in izip(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):
print x

但它给了我:

('AAA', 'M', '00:00')
('BBB', 'Q', '01:00')
('CCC', 'S', '02:00')

我要:

('AAA', 'M', '00:00')
('AAA', 'M', '01:00')
('AAA', 'M', '02:00')
.
.

('CCC', 'B', '03:00')

其实我想要这个:

for word, letter, hours in [cartesian product of 3 lists above]
if myfunction(word,letter,hours):
var_word_letter_hours += 1

最佳答案

您想使用 product列表的:

from itertools import product

for word, letter, hours in product(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):

演示:

>>> from itertools import product
>>> for word, letter, hours in product(["AAA", "BBB", "CCC"], ["M", "Q", "S", "K", "B"], ["00:00", "01:00", "02:00", "03:00"]):
... print word, letter, hours
...
AAA M 00:00
AAA M 01:00
AAA M 02:00
AAA M 03:00
...
CCC B 00:00
CCC B 01:00
CCC B 02:00
CCC B 03:00

关于python - 如何迭代列表的笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12237283/

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