将列表附加到列表中的列表末尾

时间:2013-05-21 09:55:02

标签: python list 2d

有没有一种好方法可以将2个列表“合并”在一起,这样一个列表中的项目可以附加到列表中列表的末尾?例如......

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 个答案:

答案 0 :(得分: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项,则此解决方案无需错误,按索引修改列表会冒这些潜在的问题。

答案 1 :(得分: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]]

答案 2 :(得分:0)

zip(*zip(*a2dList)+[otherList])
相关问题