将一维数组的元素插入二维数组中的特定位置

Inserting Elements of 1D array to specific location in 2D array

正在尝试使用 insert() 方法组合 1 维和 2 维 list/arrays 包含的字符串。

然而,从 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() 还是应该在使用任何方法之前引入列表连接?

如有任何见解,我们将不胜感激!

正如评论中所讨论的,您可以使用 enumeratezip 通过列表理解来实现此目的。您可以使用 enumeratelist1 获取索引和子列表,使用 index 到 select 来自 list2 的适当值附加到每个子列表:

list1 = [l1 + [list2[-i-1]] for i, l1 in enumerate(list1)]

或者你可以 zip 一起 list1 和相反的 list2:

list1 = [l1 + [l2] for l1, l2 in zip(list1, list2[::-1])]

或者您可以只使用一个简单的 for 循环就地修改 list1:

for i in range(len(list1)):
    list1[i].append(list2[-i-1])

对于所有这些,输出是:

[['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']]