[英]Create list of all possible tuples from lists
I would like to create a list of 3-tuples in Python.我想在 Python 中创建一个三元组列表。 These 3-tuples should hold all possible combinations of numbers, where at least one item from each list is included.
这些 3 元组应该包含所有可能的数字组合,其中每个列表中至少包含一个项目。 Is there any way to do this in an efficient manner?
有没有办法以有效的方式做到这一点?
I only thought of the possibility of nested for loops, like this:我只想到了嵌套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)
However, this seems very inefficient.但是,这似乎非常低效。 Also, when I try to run this, triplets is not a list of tuples but a list of single numbers, what did I do wrong there?
另外,当我尝试运行它时,triplets 不是元组列表而是单个数字列表,我在那里做错了什么?
With itertools.product , I guess you could do something like this:使用itertools.product ,我想您可以执行以下操作:
from itertools import product
l1 = [1, 2, 3]
l2 = [4, 5]
result = product(l1, l2, l2)
print(list(result))
Previous code prints:以前的代码打印:
[(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)]
You can use a simple list comprehension :您可以使用简单的列表理解:
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.