[英]Inserting Elements of 1D array to specific location in 2D array
Attempting to combine 1 & 2 dimensional list/arrays containing strings using the insert()
method.尝试使用
insert()
方法组合包含字符串的一维和二维列表/数组。
However getting a specific element from the 1D list and placing that into a specific location within the 2D list is where Im stuck.然而,从一维列表中获取特定元素并将其放入二维列表中的特定位置是我卡住的地方。
Here is a simplified version of what the goal is;这是目标的简化版本;
#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']]
Here is the isolated block of code from the script which Im trying to attempt this with;这是我尝试使用的脚本中的隔离代码块;
#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)
output of the code above;上面代码的输出;
[['a1', 'b1', 'c3', 'c2', 'c1'], ['a2', 'b2', 'c3', 'c2', 'c1'], ['a3', 'b3', 'c3', 'c2', 'c1']]
What is the best & most efficient way to go about returning the desired output?返回所需输出的最佳和最有效的方法是什么? Should I use the
append()
method rather than insert()
or should i introduce list concatenation before using any methods?我应该使用
append()
方法而不是insert()
还是应该在使用任何方法之前引入列表连接?
Any insight would be appreciated!任何见解将不胜感激!
As discussed in the comments, you can achieve this via a list comprehension using enumerate
or zip
.正如评论中所讨论的,您可以通过使用
enumerate
或zip
的列表理解来实现这一点。 You can use enumerate
to get the index and sublist from list1
, using the index
to select the appropriate value from list2
to append to each sublist:您可以使用
enumerate
从list1
获取索引和子列表,使用index
从list2
选择适当的值以附加到每个子列表:
list1 = [l1 + [list2[-i-1]] for i, l1 in enumerate(list1)]
or you can zip
together list1
and the reversed list2
:或者您可以将
list1
和反向的list2
zip
在一起:
list1 = [l1 + [l2] for l1, l2 in zip(list1, list2[::-1])]
Or you can just use a simple for
loop to modify list1
in place:或者你可以使用一个简单的
for
循环来修改list1
到位:
for i in range(len(list1)):
list1[i].append(list2[-i-1])
For all of these the output is:对于所有这些,输出是:
[['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.