1

たとえば、Python に配列があるとします。

my_array = np.array([10, -5, 4, ...])
my_indices = np.array([0, 3, 10, ...])

どうすれば効率的に取得できますか:

  1. にないインデックスのリストmy_arraymy_indices
  2. 参照されていない要素のリスト(1 で簡単ですが、おそらく直接的な方法があります)my_arraymy_indices
4

4 に答える 4

5

私はそれを次のようにするかもしれません:

>>> import numpy as np
>>> a = np.random.random(10)  # set up a random array to play with
>>> a
array([ 0.20291643,  0.89973074,  0.14291639,  0.53535553,  0.21801353,
        0.05582776,  0.64301145,  0.56081956,  0.85771335,  0.6032354 ])
>>>
>>> b = np.array([0,5,6,9])  # indices we *don't want*
>>> mask = np.ones(a.shape,dtype=bool)
>>> mask[b] = False          # Converted to a mask array of indices we *do want*
>>> mask
array([False,  True,  True,  True,  True, False, False,  True,  True, False], dtype=bool)
>>>
>>> np.arange(a.shape[0])[mask]  #This gets you the indices that aren't in your original
array([1, 2, 3, 4, 7, 8])
>>> a[mask]  #This gets you the elements not in your original.
array([ 0.89973074,  0.14291639,  0.53535553,  0.21801353,  0.56081956,
        0.85771335])
于 2013-02-11T01:09:00.423 に答える
2

パート 1 では、Python の組み込みsetクラスを使用して、2 つのセットの違いを利用できます。

my_array = [1,2,3,4]
my_indices = [3,4,5]

print list(set(my_array) - set(my_indices))

出力します: [1, 2].


編集

my_arrayにないのインデックスのリストを返すには、my_indicesリスト内包表記を使用できます。

my_array = [1,2,3,4]
my_indices = [0,3]

print [x for x in range(len(my_array)) if x not in my_indices]

次のようにも表現できます。

temp = []
for x in range(len(my_array)):
  if x not in my_indices:
    temp.append(x) 

これにより、インデックスが返されます[1,2]

要素のリストを取得したい場合は、ステートメントを次のように変更できます。

print [my_array[x] for x in range(len(my_array)) if x not in my_indices]

どちらが出力されますか[2,3]

于 2013-02-11T00:51:37.137 に答える
1

最初の質問:

my_indices_set = set(my_indices)
[i for i, x in enumerate(my_array) if i not in my_indices]

2 番目の質問:

[x for x in my_array if x not in my_indices_set]

セットを使用した方が効率的ですが、そもそもセットを作成するコストがかかります

于 2013-02-11T00:51:54.813 に答える
1

リスト内包表記を使用できます

array_len = len(my_array)
missing_indices = [i for i in my_indices
                   if i < 0 or i >= array_len]
elems = [my_array[i] for i in missing_indices]
于 2013-02-11T01:02:55.817 に答える