[英]How to iterate through the Cartesian product of ten lists (ten elements each) faster? (Probability and Dice)
[英]How to iterate in a cartesian product of lists
我想使用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
您要使用列表的產品 :
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
使用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')
僅作記錄,另一個解決方案只是嵌套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)
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.