我是 python 的新手,我有两个列表:
l1 = ['a','b','c','d']
l2 = ['new']
我想得到这样的新列表
l3 = [('a','new'),('b','new'),('c','new'),('d','new')]
结合这两个列表的最佳方法是什么?
我是 python 的新手,我有两个列表:
l1 = ['a','b','c','d']
l2 = ['new']
我想得到这样的新列表
l3 = [('a','new'),('b','new'),('c','new'),('d','new')]
结合这两个列表的最佳方法是什么?
>>> from itertools import product
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> list(product(l1,l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
如果l2
总是只有一个元素,则无需使事情过于复杂
l3 = [(x, l2[0]) for x in l1]
请参阅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))
>>> from itertools import repeat
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> zip(l1,repeat(*l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]
您可以简单地使用列表推导而无需任何功能:
l3 = [(x, y) for x in l1 for y in l2]