突然想到

python 要如何在假設有3組list情況下

從3組list 內的元素各取一個,列出所有取出的組合?

一般想到會用遞迴來做

例如以下這樣

 

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']

for item1 in list1:
    for item2 in list2:
        for item3 in list3:
            print(item1, item2, item3)

 

 

但是我不想要用到遞迴

該怎麼做呢?

可以參考 itertools 的 product

 

from itertools import product

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = ['x', 'y', 'z']

# 使用itertools.product生成所有组合
combinations = list(product(list1, list2, list3))

# 輸出所有组合
for combination in combinations:
    print(combination)

 

 

就會輸出以下內容

 

(1, 'a', 'x')
(1, 'a', 'y')
(1, 'a', 'z')
(1, 'b', 'x')
(1, 'b', 'y')
(1, 'b', 'z')
(1, 'c', 'x')
(1, 'c', 'y')
(1, 'c', 'z')
(2, 'a', 'x')
(2, 'a', 'y')
(2, 'a', 'z')
(2, 'b', 'x')
(2, 'b', 'y')
(2, 'b', 'z')
(2, 'c', 'x')
(2, 'c', 'y')
(2, 'c', 'z')
(3, 'a', 'x')
(3, 'a', 'y')
(3, 'a', 'z')
(3, 'b', 'x')
(3, 'b', 'y')
(3, 'b', 'z')
(3, 'c', 'x')
(3, 'c', 'y')
(3, 'c', 'z')

 

 

有時候還真的會需要用到這功能哩