I am a newbie in python, I have two lists:
l1 = ['a','b','c','d']
l2 = ['new']
i want to get new list like this
l3 = [('a','new'),('b','new'),('c','new'),('d','new')]
What is the best way to combine the two lists?
>>> 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]
See the itertools docs .
In particular, use product for a Cartesian 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')]
You can simply take use of list comprehension without any functions:
l3 = [(x, y) for x in l1 for y in l2]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.