how to produce a nested list from two lists in python

泄露秘密 提交于 2019-12-06 15:33:11
>>> from itertools import product
>>> l1 = ['a','b','c','d']
>>> l2 = ['new']
>>> list(product(l1,l2))
[('a', 'new'), ('b', 'new'), ('c', 'new'), ('d', 'new')]

If l2 always just has the one element there is no need to overcomplicate things

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]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!