我有兩個串列,都包含相同維度的 numpy 陣列。
為了簡化,a這里b用整數和字串表示:
a = [0, 1, 2, 3]
b = ['a', 'b', 'c']
我想在從 1 開始的每個位置為bin插入一個值a,并回傳一個 numpy 陣列串列。像這樣:
[array(['0', 'a', '2', '3'], dtype='<U21'),
array(['0', '1', 'b', '3'], dtype='<U21'),
array(['0', '1', '2', 'c'], dtype='<U21')]
它需要可擴展,因為 和 的長度總是未知的a,b并且a總是在索引 0 處有一個額外的物件。
有任何想法嗎?
uj5u.com熱心網友回復:
a = [1,2,3]
b = ["a","b","c"]
ls = []
for i,k in enumerate(b):
c = a[:]
c.insert(i 1,k)
ls.append(c)
這將填寫ls您需要的串列。
uj5u.com熱心網友回復:
這可以通過正常的 for 回圈來解決:
import numpy as np
a = [0, 1, 2, 3]
b = ['a', 'b', 'c']
l = []
#for dealing with the extra object we start iterating from 1
for i in range(0,3):
a = [0, 1, 2, 3] #we keep 'a' or a copy of the original list
a[i 1] = b[i] #we assign a 'b' value in 'a'
l.append(np.asarray(a)) #we save it and go to the next position
print(l)
輸出:
[array(['0', 'a', '2', '3'], dtype='<U21'),
array(['0', '1', 'b', '3'], dtype='<U21'),
array(['0', '1', '2', 'c'], dtype='<U21')]
在串列推導中分配陳述句不是一個好習慣,因此建議使用 for 回圈,您可以在這篇文章中獲得更多示例: 使用 python 串列推導更新字典值
輸出:[1]:https ://i.stack.imgur.com/jx160.png
uj5u.com熱心網友回復:
你可以試試:
a = [0, 1, 2, 3]
b = ['a', 'b', 'c']
arr = np.tile(np.array(a, dtype='str'), (len(a) - 1, 1))
idx = np.arange(len(arr) 1)
arr[idx[:-1], idx[1:]] = b
result = list(arr)
結果:
[array(['0', 'a', '2', '3'], dtype='<U1'),
array(['0', '1', 'b', '3'], dtype='<U1'),
array(['0', '1', '2', 'c'], dtype='<U1')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464610.html
