起初我有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)
但现在我不知道如何扩展以获得其他元素..
答案 0 :(得分:7)
使用列表理解:
newList = [x[: 2] + y + x[-1:] for x, y in zip(l1, l2)]
答案 1 :(得分:3)
使用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']]