2012-05-01 80 views

回答

5
>>> from itertools import product 
>>> l1 = ['a','b','c','d'] 
>>> l2 = ['new'] 
>>> list(product(l1,l2)) 
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')] 
2
>>> from itertools import repeat 
>>> l1 = ['a','b','c','d'] 
>>> l2 = ['new'] 
>>> zip(l1,repeat(*l2)) 
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')] 
+0

谢谢@jamylak。我工作。 – kuslahne

+0

我认为我的其他解决方案更好:D – jamylak

+0

我会使用'repeat'而不是'cycle'。 –

3

itertools docs

特别是,使用产品的笛卡尔乘积:

from itertools import product: 
l1 = ['a','b','c','d'] 
l2 = ['new'] 
# Cast to list for l3 to be a list since product returns a generator 
l3 = list(product(l1, l2)) 
5

如果l2永远只是有一个元素,没有必要过分复杂化的东西

l3 = [(x, l2[0]) for x in l1] 
+1

这也是有用的答案。谢谢。 – kuslahne

0

你可以简单地使用列表没有任何功能的理解:

l3 = [(x,y)for x in l1 for y in l2]