[英]Inserting Elements of 1D array to specific location in 2D array
嘗試使用insert()
方法組合包含字符串的一維和二維列表/數組。
然而,從一維列表中獲取特定元素並將其放入二維列表中的特定位置是我卡住的地方。
這是目標的簡化版本;
#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()
還是應該在使用任何方法之前引入列表連接?
任何見解將不勝感激!
正如評論中所討論的,您可以通過使用enumerate
或zip
的列表理解來實現這一點。 您可以使用enumerate
從list1
獲取索引和子列表,使用index
從list2
選擇適當的值以附加到每個子列表:
list1 = [l1 + [list2[-i-1]] for i, l1 in enumerate(list1)]
或者您可以將list1
和反向的list2
zip
在一起:
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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.