有没有一种好方法可以将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],[....]]
Run Code Online (Sandbox Code Playgroud)
我不确定a2dList是否由字符串构成并且otherList是数字是否重要...我已经尝试过append但我最终得到了
theFinalList=[['a','1','2','3','4'],['b','5','6','7','8'],[.......],[9,8,7,6,5]
Run Code Online (Sandbox Code Playgroud)
>>> 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]]
Run Code Online (Sandbox Code Playgroud)
在Python 2.x上考虑使用itertools.iziplazy压缩:
from itertools import izip # returns iterator instead of a list
Run Code Online (Sandbox Code Playgroud)
还要注意,zip在到达最短可迭代结束时将自动停止,因此如果otherList或a2dList只有1项目,此解决方案将无误地工作,通过索引修改列表可能会冒这些潜在问题.
| 归档时间: |
|
| 查看次数: |
198 次 |
| 最近记录: |