[英]Create list of all possible tuples from lists
我想在 Python 中創建一個三元組列表。 這些 3 元組應該包含所有可能的數字組合,其中每個列表中至少包含一個項目。 有沒有辦法以有效的方式做到這一點?
我只想到了嵌套for循環的可能性,如下所示:
def triplets_dos_listas(L1,L2):
triplets = []
#create list triplets
for i in range(len(L1)):
#add triplet to list triplets for all triplets with one from l1 and 2 l2
for j in range(len(L2)):
for k in range(len(L2)):
triplets += tuple([L1[i], L2[j],L2[k]])
#repeat the process for the combinations (L1,L2,L1), (L2,L1,L1) and (L2,L2,L1)
print(triplets)
但是,這似乎非常低效。 另外,當我嘗試運行它時,triplets 不是元組列表而是單個數字列表,我在那里做錯了什么?
使用itertools.product ,我想您可以執行以下操作:
from itertools import product
l1 = [1, 2, 3]
l2 = [4, 5]
result = product(l1, l2, l2)
print(list(result))
以前的代碼打印:
[(1, 4, 4), (1, 4, 5), (1, 5, 4), (1, 5, 5), (2, 4, 4), (2, 4, 5), (2, 5, 4), (2, 5, 5), (3, 4, 4), (3, 4, 5), (3, 5, 4), (3, 5, 5)]
您可以使用簡單的列表理解:
def triplets_dos_listas(l1, l2):
return [(a,b,c) for a in l1 for b in l2 for c in l2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.