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

举个例子。

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)]

当前回答

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

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

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

我也喜欢其他的答案!

其他回答

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

>>> [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']

找出大量列表的所有组合的最好方法是:

import itertools
from pprint import pprint

inputdata = [
    ['a', 'b', 'c'],
    ['d'],
    ['e', 'f'],
]
result = list(itertools.product(*inputdata))
pprint(result)

结果将是:

[('a', 'd', 'e'),
 ('a', 'd', 'f'),
 ('b', 'd', 'e'),
 ('b', 'd', 'f'),
 ('c', 'd', 'e'),
 ('c', 'd', 'f')]

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

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

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

我也喜欢其他的答案!

最简单的方法是使用itertools.product:

a = ["foo", "melon"]
b = [True, False]
c = list(itertools.product(a, b))
>> [("foo", True), ("foo", False), ("melon", True), ("melon", False)]

没有itertools作为扁平列表:

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

或者在python2中:

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