在lis中,在列表末尾追加一个列表

2024-07-04 13:01:27 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一个好方法可以将两个列表“合并”在一起,以便一个列表中的一个项目可以附加到列表的末尾?例如。。。在

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是由字符串组成的,而其他列表是数字是否重要。。。 我试过append,但最后

^{2}$

Tags: 项目方法字符串列表数字末尾appendotherlist
3条回答
>>> 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]]

在Python2.x上,考虑使用itertools.izip代替延迟压缩:

^{pr2}$

还要注意,zip将在到达最短iterable的末尾时自动停止,因此如果otherList或{}只有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]]
zip(*zip(*a2dList)+[otherList])

相关问题 更多 >

    热门问题