1

我是 python 的新手,我有两个列表:

l1 = ['a','b','c','d']
l2 = ['new']

我想得到这样的新列表

l3 = [('a','new'),('b','new'),('c','new'),('d','new')]

结合这两个列表的最佳方法是什么?

4

5 回答 5

5
>>> from itertools import product
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> list(product(l1,l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
于 2012-05-01T06:34:28.473 回答
5

如果l2总是只有一个元素,则无需使事情过于复杂

l3 = [(x, l2[0]) for x in l1]
于 2012-05-01T06:42:06.137 回答
3

请参阅itertools 文档

特别是,将 product 用于笛卡尔积:

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))  
于 2012-05-01T06:35:27.127 回答
2
>>> from itertools import repeat
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> zip(l1,repeat(*l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
于 2012-05-01T06:31:03.577 回答
0

您可以简单地使用列表推导而无需任何功能:

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

于 2012-05-01T09:23:38.240 回答