gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:29 26 4
gpt4 key购买 nike

有没有一种好方法可以将 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]

最佳答案

>>> 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 项,此解决方案可以正常工作,按索引修改列表可能会出现这些潜在问题。

关于python - 将列表附加到列表中列表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16667120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com