DISLCAIMER:我是Python新手
我想在Python中通过组合2个现有的2-D列表来创建一个连接的2-D列表。我从两个列表开始:
listA = [[a, b, c], [1, 2, 3]]
listB = [[d, e, f], [4, 5, 6]]我想创建一个新的列表(同时保留listA和listB):
listC = [[a, b, c, d, e, f], [1, 2, 3, 4, 5, 6]]如果我尝试像添加一维列表一样添加它们,我会得到:
listA + listB
result = [[a, b, c], [1, 2, 3], [d, e, f], [4, 5, 6]]我也尝试过:
listC = listA
listC[0] += listB[0]
listC[1] += listB[1]
# This may be giving me the result I want, but it corrupts listA:
Before: listA = [[a, b, c], [1, 2, 3]
After: listA = [[a, b, c, d, e, f], [1, 2, 3, 4, 5, 6]]什么是创建我想要的数据的新列表的正确方法?
我也可以使用元组:
listC = [(a, 1), (b, 2), (c, 3), (d, 4), (e, 5), (f, 6)]但也不知道具体的方法。
我目前使用的是Python2.7 (raspberry pi运行raspbian Jessie),但如果需要的话,Python3.4也可以使用。
发布于 2016-10-14 02:00:39
有几种方法:
listC = [listA[0] + listB[0], listA[1] + listB[1]]
listC = [x + y for x, y in zip(listA, listB)]可能是最简单的两个
发布于 2016-10-14 01:58:17
创建一个新的列表,例如,使用list-comprehension
listC = [a+b for a,b in zip(listA, listB)]发布于 2016-10-14 02:01:40
如果你想了解更多,这里有一个函数式的方法:
In [13]: from operator import add
In [14]: from itertools import starmap
In [15]: list(starmap(add, zip(listA, listB)))
Out[15]: [['a', 'b', 'c', 'd', 'e', 'f'], [1, 2, 3, 4, 5, 6]]注意,由于starmap返回一个迭代器,如果您不想要列表中的结果(如果您只想迭代结果),那么在这里就不应该使用list()。
https://stackoverflow.com/questions/40027837
复制相似问题