[英]Initialise numpy array of unknown length
我希望能夠即時“構建”一個 numpy 數組,我事先不知道這個數組的大小。
例如我想做這樣的事情:
a= np.array()
for x in y:
a.append(x)
這將導致 a 包含 x 的所有元素,顯然這是一個微不足道的答案。 我只是好奇這是否可能?
構建一個 Python 列表並將其轉換為 Numpy 數組。 每次追加需要分攤 O(1) 時間 + O( n ) 轉換為數組,總共 O( n )。
a = []
for x in y:
a.append(x)
a = np.array(a)
你可以這樣做:
a = np.array([])
for x in y:
a = np.append(a, x)
由於 y 是一個可迭代的,我真的不明白為什么要追加調用:
a = np.array(list(y))
會做,而且速度要快得多:
import timeit
print timeit.timeit('list(s)', 's=set(x for x in xrange(1000))')
# 23.952975494633154
print timeit.timeit("""li=[]
for x in s: li.append(x)""", 's=set(x for x in xrange(1000))')
# 189.3826994248866
對於后代,我認為這更快:
a = np.array([np.array(list()) for _ in y])
您甚至可以傳入一個生成器(即 [] -> ()),在這種情況下,內部列表永遠不會完全存儲在內存中。
回應以下評論:
>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object)], dtype=object)
a = np.empty(0)
for x in y:
a = np.append(a, x)
我寫了一個小實用函數。 (上面的大多數答案都很好。我覺得這看起來更好)
def np_unknown_cat(acc, arr):
arrE = np.expand_dims(arr, axis=0)
if acc is None:
return arrE
else:
return np.concatenate((acc, arrE))
您可以使用上述功能如下:
acc = None # accumulator
arr1 = np.ones((3,4))
acc = np_unknown_cat(acc, arr1)
arr2 = np.ones((3,4))
acc = np_unknown_cat(acc, arr2)
list1 = []
size = 1
option = "Y"
for x in range(size):
ele = input("Enter Element For List One : ")
list1.append(ele)
while(option == "Y"):
option = input("\n***Add More Element Press Y ***: ")
if(option=="Y"):
size = size + 1
for x in range(size):
ele = input("Enter Element For List Element : ")
list1.append(ele)
size = 1
else:
break;
print(list1)
拿:
list1 = [] # Store Array Element
size = 1 # Rune at One Time
option = "Y" # Take User Choice
執行:
size = 1
size = size + 1
在一定大小范圍內運行另一個 for 循環
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.