[英]Create all possible combination from a list without any package
suppose I have a list in python that is假设我在 python 中有一个列表
['hello', 'yo', 'great', 'this', 'cool', 'fam']
how do I get all the possible 2 combinations that I can have from this list in tuples;我如何从元组中的这个列表中获得我可以拥有的所有可能的 2 种组合; output example:输出示例:
[ ('hello','hello'),('hello','yo'),('hello', 'great'),...,('yo','hello'),('yo', 'yo') .... ]
and so on等等
no packages allowed不允许包裹
You can have a look at https://docs.python.org/2/library/itertools.html#itertools.permutations , more specific to the class itertools.permutations(iterable[, r])
您可以查看https://docs.python.org/2/library/itertools.html#itertools.permutations ,更具体到类itertools.permutations(iterable[, r])
As soon as you have already a tuple and you just need the combinations of 2 elements you can edit the code like只要您已经有了一个元组,并且只需要 2 个元素的组合,您就可以编辑代码,例如
n = len(my_tuple)
indices = range(n)
cycles = range(n, n-2, -1)
yield tuple(my_tuple[i] for i in indices[:2])
while n:
for i in reversed(range(2)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(my_tuple[i] for i in indices[:2])
break
else:
return
where my_tuple
is the input tuple其中my_tuple
是输入元组
Well, the desired output is simply the result of the Cartesian product (pairs and order matter), so either you can try this here or by using list comprehension:好吧,所需的输出只是笛卡尔积(对和顺序问题)的结果,因此您可以在这里尝试或使用列表理解:
[(entry1, entry2) for entry1 in myList for entry2 in myList]
with myList is your input list. myList 是您的输入列表。
Take the cartesian product between your list and itself:在你的列表和它本身之间取笛卡尔积:
l1 = [hello,yo,great,this,cool,fam]
l2 = [hello,yo,great,this,cool,fam]
l1_x_l2 = [(i1, i2) for i1 in l1 for i2 in l2]
or more simply just do或者更简单地做
l = [hello,yo,great,this,cool,fam]
l_x_l = [(i1, i2) for i1 in l for i2 in l]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.