我很难理解我要实现的一个算法。我有两个链表,我想从这两个链表中取特定的组合。

举个例子。

names = ['a', 'b']
numbers = [1, 2]

这种情况下的输出将是:

[('a', 1), ('b', 2)]
[('b', 1), ('a', 2)]

我可能有更多的名称比数字,即len(名称)>= len(数字)。下面是一个有3个名字和2个数字的例子:

names = ['a', 'b', 'c']
numbers = [1, 2]

输出:

[('a', 1), ('b', 2)]
[('b', 1), ('a', 2)]
[('a', 1), ('c', 2)]
[('c', 1), ('a', 2)]
[('b', 1), ('c', 2)]
[('c', 1), ('b', 2)]

当前回答

对interjay的答案进行了微小的改进,使结果作为一个平坦的列表。

>>> list3 = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
>>> import itertools
>>> chain = itertools.chain(*list3)
>>> list4 = list(chain)
[('a', 1), ('b', 2), ('a', 1), ('c', 2), ('b', 1), ('a', 2), ('b', 1), ('c', 2), ('c', 1), ('a', 2), ('c', 1), ('b', 2)]

来自此链接的引用

其他回答

你可能想尝试一行列表理解:

>>> [name+number for name in 'ab' for number in '12']
['a1', 'a2', 'b1', 'b2']
>>> [name+number for name in 'abc' for number in '12']
['a1', 'a2', 'b1', 'b2', 'c1', 'c2']

注:此答案是针对上述特定问题的。如果你从谷歌来到这里,正在寻找一种在Python中获得笛卡尔积的方法,itertools。产品或一个简单的列表理解可能是你正在寻找的-见其他答案。


假设len(list1) >= len(list2)。然后,您似乎想要从list1中获取长度len(list2)的所有排列,并将它们与list2中的项匹配。在python中:

import itertools
list1=['a','b','c']
list2=[1,2]

[list(zip(x,list2)) for x in itertools.permutations(list1,len(list2))]

返回

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]

对interjay的答案进行了微小的改进,使结果作为一个平坦的列表。

>>> list3 = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
>>> import itertools
>>> chain = itertools.chain(*list3)
>>> list4 = list(chain)
[('a', 1), ('b', 2), ('a', 1), ('c', 2), ('b', 1), ('a', 2), ('b', 1), ('c', 2), ('c', 1), ('a', 2), ('c', 1), ('b', 2)]

来自此链接的引用

可能比上面最简单的一个更简单:

>>> a = ["foo", "bar"]
>>> b = [1, 2, 3]
>>> [(x,y) for x in a for y in b]  # for a list
[('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)]
>>> ((x,y) for x in a for y in b)  # for a generator if you worry about memory or time complexity.
<generator object <genexpr> at 0x1048de850>

没有任何进口

或者用KISS回答简短的清单:

[(i, j) for i in list1 for j in list2]

性能不如itertools,但你使用的是python,所以性能已经不是你最关心的…

我也喜欢其他的答案!