【发布时间】:2021-03-13 15:45:10
【问题描述】:
我有两个数组:
X = [1,2,3,4,5]
和
Y = [10,20,30,40,50]
我正在尝试将两个数组合并为一个数组,其中数组 X 中的项目对应于 row=0,数组 Y 中的项目对应于行=1。
所以新数组看起来像:
combined = [[1,10],[2,20],[3,30],[4,40],[5,50]]
我尝试了以下方法:
for element in combined:
for item in X:
element[0] = item
这应该将 X 中的所有元素添加到 combined 的第一行 像这样:
combined = [[1, 0],[2, 0],[3, 0],[4, 0],[5, 0]]
但是,它并没有像我预期的那样工作,因为它给了我以下结果:
combined = [[1, 0],[1, 0],[1, 0],[1, 0],[1, 0]]
【问题讨论】:
-
试试
list(zip(X,Y)) -
这能回答你的问题吗? How to merge lists into a list of tuples?
-
@Pygirl,它完成了部分工作。它返回 [(1,10), (2,10)] 而不是 [[1,10], [2,10]]。所以它返回对象
-
How to debug small programs. | What is a debugger and how can it help me diagnose problems? 您将
element的第一个索引设置为X的每个元素。在内部 for 循环结束时,第一个索引设置为X的最后一个元素。combined中的所有element都会发生这种情况。只需要将X的对应元素设置为element的第一个索引 -
然后将它们映射到一个列表中:
list(map(list, zip(X, Y)))