簡體   English   中英

如何獲取numpy數組的每個元素?

[英]How to get each element of numpy array?

我有一個numpy數組,如下所示:

鍵將存儲一些值。 例如按鍵[2,3,4,7,8]

如何獲取索引4並將索引存儲在int變量中?

例如,索引值4為2,因此2將存儲在int變量中。

我嘗試了以下代碼段

//enter code here

for i in np.nditer(Keys):
      print(keys[i]);

//enter code here

我正在使用python 3.5 Spyder 3.5.2 Anaconda 4.2.0

keys是列表還是numpy數組

 keys = [[2,3,4,7,8]   # or
 keys = np.array([2,3,4,7,8])

您無需反復查看其中任何一個的元素。 但是你可以做

 for i in keys:
     print(i)
 for i in range(len(keys)):
     print(keys[i])
 [i for i in keys]

這些工作要么。

如果要使用值4的索引,則列表具有一個方法:

 keys.index(4)

用於數組

 np.where(keys==4)

是一段有用的代碼。

 np.in1d(keys, 4)
 np.where(np.in1d(keys, 4))

忘了np.nditer 那是用於高級編程,而不是常規迭代。

有幾種方法。 如果列表不是太大,則:

where_is_4 = [e for i,e in enumerate(Keys) if i==4][0]

它的作用是使用枚舉器遍歷列表,並在每次出現值“ 4”時創建一個包含枚舉器值的列表。

為什么不做:

for i in range( len( Key ) ):
    if ( Key[ i ] == 4 ):
      print( i )

您可以使用以下命令找到值為4所有索引:

>>> keys = np.array([2,3,4,7,8])
>>> np.flatnonzero(keys == 4)
array([2])

有一個本地的numpy方法,稱為where

在某些條件為真的情況下,它將返回索引數組。 因此,如果列表不為空,則只需選擇第一個條目:

N = 4
indicies = np.where(x==N)[0]
index = None
if indicies:
    index = indicies[0]

在這里使用numpy.where(condition)將是一個不錯的選擇。 從下面的代碼中,您可以獲得4的位置。

import numpy as np
keys = np.array([2,3,4,7,8])
result = np.where(keys==4)
result[0][0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM