2015-10-13 30 views
1
import numpy as np 

S = np.array(l) 
for i in range(1, l): 
    random_int = randint(0, 1) 
    np.append(S, random_int) 

我創建了一個大小爲l的numpy數組,並用零和一個填充它。假設我想打印數組的第三個元素。我怎麼做?如何在numpy數組中調用位置X的元素?

如果鍵入

print(S[2]) 

我得到以下錯誤:

IndexError: too many indices for array 

回答

2

我想簡單地做以這種方式來生成L個隨機數0和1之間:

L = 10 
S = np.random.random_integers(0,1,L) 
print S 
print S[2] 

回報:

[1 0 0 1 0 0 1 1 0 1] 
0 
+0

簡單而優雅我喜歡它 – Aventinus

1

np.append(S, random_int)追加random_int到陣列S副本。您需要在for循環中使用S = np.append(S, random_int)

import numpy as np 
from random import randint 

l = 5 
S = np.array(l) 
for i in range(1, l): 
    random_int = randint(0, 1) 
    S = np.append(S, random_int) 

print(S) 
print(S[2]) 

輸出

[5 1 1 0 1] 
1 
1

首先,S = np.array(l)不會產生長度爲l的數組,但長度爲1的數組的唯一條目是l。 所以,你可以接着用S = np.zeros(l)(創建長度l全是零的數組替換該行 ,在你的循環,你必須做到:。

for i in range l: 
    S[i] = randint(0, 1) 

這僅僅是指出你的錯誤,因爲@。法比奧說,你可以在一條線上做到這一點

+0

謝謝,我剛開始使用numpy,所以這樣的事情輕易欺騙我。 – Aventinus

相關問題