16

たとえば、任意の数の要素を持つ 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
4

3 に答える 3

24

リストの製品を使用したい:

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
于 2012-09-02T15:39:43.457 に答える
7

使用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')
于 2012-09-02T15:43:17.020 に答える