我是python的新手, 我有两个清单:
l1 = ['a','b','c','d']
l2 = ['new']
我希望得到像这样的新列表
l3 = [('a','new'),('b','new'),('c','new'),('d','new')]
合并两个列表的最佳方法是什么?
答案 0 :(得分:5)
>>> from itertools import product
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> list(product(l1,l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
答案 1 :(得分:5)
如果l2
总是只有一个元素,则不需要使事情过于复杂
l3 = [(x, l2[0]) for x in l1]
答案 2 :(得分: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))
答案 3 :(得分:2)
>>> from itertools import repeat
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> zip(l1,repeat(*l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
答案 4 :(得分:0)
您可以简单地使用列表推导而无需任何功能:
l3 = [(x,y),对于l中的x,对于l in中的y]