繁体   English   中英

连接列表列表

[英]Concatenate a list of lists

起初我有2个列表,l1和l2

l1 = [['a','1','b','c','now'],['d','2','e','f','tomorrow']] 

l2 = [['11:30', '12:00'],['13:00', '13:30']]

我想要的是用l1中每个列表的前两个元素创建一个新列表列表,得到: newList = [['a', '1'], ['d', '2']]

然后,从newList中的每个列表中,我想从l2中添加一个列表,以获得:

newList = [['a', '1', '11:30', '12:00'], ['d', '2', '13:00', '13:30']]

最后,我想添加l1中每个列表的最后一个元素:

newList = [['a', '1', '11:30', '12:00','now'], ['d', '2', '13:00', '13:30','tomorrow']]

到目前为止,我所拥有的是:

newList =[]

for i in l1:
   names = i[:2]
   newList.append(names)

但是现在我不知道该如何扩展以获取其他元素。

使用列表理解:

newList = [x[: 2] + y + x[-1:] for x, y in zip(l1, l2)]

使用zip和列表推导。

>>> l1 = [['a','1','b','c','now'],['d','2','e','f','tomorrow']]
>>> l2 = [['11:30', '12:00'],['13:00', '13:30']]
>>> [[x[0], x[1]] + y + [x[-1]] for x, y in zip(l1, l2)]
[['a', '1', '11:30', '12:00', 'now'], ['d', '2', '13:00', '13:30', 'tomorrow']]
>>> [x[:2] + y + [x[-1]] for x, y in zip(l1, l2)]
[['a', '1', '11:30', '12:00', 'now'], ['d', '2', '13:00', '13:30', 'tomorrow']]

暂无
暂无

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

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