繁体   English   中英

如何从python中的两个列表生成嵌套列表

[英]how to produce a nested list from two lists in python

我是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文档

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

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 = [对于l1中的x对于l2中的y为((x,y)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM