如何迭代列表的笛卡尔积

时间:2012-09-02 15:38:11

标签: python list for-loop loops

我想使用包含任意数量元素的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

3 个答案:

答案 0 :(得分:16)

您想使用列表的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

答案 1 :(得分:5)

使用itertools.product

import itertools

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

输出:

('AAA', 'M', '00:00')
('AAA', 'M', '01:00')
...
('CCC', 'B', '02:00')
('CCC', 'B', '03:00')

答案 2 :(得分:0)

仅为记录,另一种解决方案是嵌套for循环:

for a in ["AAA", "BBB", "CCC"]:
    for b in ["M", "Q", "S", "K", "B"]:
       for c in ["00:00", "01:00", "02:00", "03:00"]:
           x = (a, b, c)
           # Use x ...

在我看来,这比找出/记住itertools.product函数的作用要清楚得多。使用它的唯一好理由是,如果你处于一个更抽象的情况;例如你需要将一个迭代器传递给一个函数,而不是立即迭代它,或者如果你有一个任意的列表列表,你想要采用笛卡尔积(在这种情况下你可以使用product(*lists))。