【发布时间】:2020-10-19 00:24:07
【问题描述】:
尝试使用insert() 方法组合包含字符串的一维和二维列表/数组。
但是,从 1D 列表中获取特定元素并将其放置到 2D 列表中的特定位置是我卡住的地方。
这是目标的简化版本;
#2D list/array
list1= [['a1','b1'], ['a2','b2'] , ['a3','b3']]
#1D list/array
list2= ['c3','c2','c1']
#desired output
list1= [['a1','b1','c1'], ['a2','b2','c2'] , ['a3','b3','c3']]
这是我尝试使用的脚本中的隔离代码块;
#loop through 1D list with a nested for-loop for 2D list and use insert() method.
#using reversed() method on list2 as this 1D array is in reverse order starting from "c3 -> c1"
#insert(2,c) is specifying insert "c" at index[2] location of inner array of List1
for c in reversed(list2):
for letters in list1:
letters.insert(2,c)
print(list1)
以上代码的输出;
[['a1', 'b1', 'c3', 'c2', 'c1'], ['a2', 'b2', 'c3', 'c2', 'c1'], ['a3', 'b3', 'c3', 'c2', 'c1']]
返回所需输出的最佳和最有效的方法是什么?我应该使用append() 方法而不是insert() 还是应该在使用任何方法之前引入列表连接?
任何见解将不胜感激!
【问题讨论】:
-
一种简单有效的方法是在外部for循环中使用“枚举”(并删除内部for循环)。它允许接收与项目并行的索引。您可以使用“list1”上的此索引来访问和修改相应的子列表。更难理解的是使用“zip”而不是直接并行地从“list2”中获取子列表和项目。
-
我看到我在这里使用内置的 enumerate 函数阅读,作为带有索引的元组作为枚举对象返回。我会先将此函数应用于一维数组 list2 吗?我也会阅读更多关于内置 zip() 函数的信息
-
其实只对(反转的)“list2”。
-
好的,我尝试了您的建议,即删除内部 for 循环并将外部 for 循环中的 enumerate 函数应用到反向 list2 中;
for c in enumerate(reversed(list2)): print(list (c))我收到的输出是[(0, 'c1'), (1, 'c2'), (2, 'c3')],这很好。现在我对如何使用这些索引来访问和修改 list1 中的子列表感到困惑。
标签: python arrays multidimensional-array concatenation nested-for-loop