2017-08-22 127 views
0

我正在尋找一個迭代器,它將python(或列表)中的多個範圍作爲輸入並返回所有可能的組合。最好在迭代器中,因此它不會將所有組合存儲在內存中。我知道如何自己編寫代碼,但在我看來,這是一個非常常見的功能,所以我無法想象它已經不存在於某些庫中。這是基本的想法:python中的多個範圍(列表,集合等)迭代器

a = range(0,2) 
b = range(2,4) 

for i,j in someFunc(a,b): 
    print(i,j) 

這則打印:

0 2 
0 3 
1 2 
1 3 

這可以ofcourse由多個循環來實現:

for i in a: 
    for j in b: 
     print(i,j) 

但我在尋找一個功能,可接受無限範圍作爲參數。這似乎是一種常見功能,但我無法在任何地方找到它。

+1

你正在尋找一個*笛卡爾積*。 –

+1

檢入標準庫的'itertools'包。 –

+0

@martijnPieters謝謝你,知道正確的術語也會幫助我解決未來的問題。 – user3053216

回答

1

你想itertools.product()

>>> from itertools import product 
>>> list(product(range(0, 2), range(2, 4))) 
[(0, 2), (0, 3), (1, 2), (1, 3)] 
1

itertools.product做了catesian產品:

>>> from itertools import product 
>>> A = [1, 2 , 3 ] 
>>> B = [3, 5, 4 ] 
>>> product(A,B) 
<itertools.product object at 0x7f4428d75e10> 
>>> for i in product(A,B): 
...  print i 
... 
(1, 3) 
(1, 5) 
(1, 4) 
(2, 3) 
(2, 5) 
(2, 4) 
(3, 3) 
(3, 5) 
(3, 4) 
>>>