将一个列表添加到另一个列表的末尾

3

有没有一种好的方法可以将两个列表合并在一起,使得一个列表中的项可以添加到另一个列表的末尾?例如...

a2dList=[['a','1','2','3','4'],['b','5','6','7','8'],[........]]
otherList = [9,8,7,6,5]

theFinalList=[['a','1','2','3','4',9],['b','5','6','7','8',8],[....]]

我不确定 a2dList 是由字符串组成的,而 otherList 是由数字组成的是否重要... 我尝试使用 append 但最终结果是

theFinalList=[['a','1','2','3','4'],['b','5','6','7','8'],[.......],[9,8,7,6,5]
3个回答

5
>>> a2dList=[['a','1','2','3','4'],['b','5','6','7','8']]
>>> otherList = [9,8,7,6,5]
>>> for x, y in zip(a2dList, otherList):
        x.append(y)


>>> a2dList
[['a', '1', '2', '3', '4', 9], ['b', '5', '6', '7', '8', 8]]

在 Python 2.x 中,考虑使用 itertools.izip 进行惰性压缩。
from itertools import izip # returns iterator instead of a list

请注意,zip 在达到最短可迭代对象的末尾时会自动停止,因此如果 otherLista2dList 仅有一个项目,则此解决方案将不会出错,但通过索引修改列表存在潜在的问题。


1
>>> a = [[1,2,3,4],[1,2,3,4]]
>>> b = [5,6]
>>> for index,element in enumerate(b):
        a[index].append(element)


>>> a
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]]

如果b比a大,它就会崩溃。 - njzk2
这个很完美,但还是谢谢大家。如果我可以再进一步...现在我需要创建另一个列表,仅包含从附加的'a2dList'中添加到每个列表末尾的数字小于某个值的项目,例如:对于a2dList中的项目:如果item<7,则将其添加到shortList中...但这并不起作用。 - user2395759

0
zip(*zip(*a2dList)+[otherList])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接