Is there a good way to 'merge' 2 lists together so an item in one list can be appended to the end of a list in a list? For example...
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],[....]]
I'm not sure if it matter that a2dList is made of strings and otherList are numbers... I've tried append
but I end up with
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]]
On Python 2.x consider using itertools.izip
instead for lazy zipping:
from itertools import izip # returns iterator instead of a list
Also note that zip
will automatically stop upon reaching the end of the shortest iterable, so if otherList
or a2dList
had only 1
item, this solution would work without error, modifying lists by index risks these potential problems.
>>> 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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.