インデックスを知って、指定されたリストからいくつかの要素を選択する必要があります。与えられたリスト [-2, 1, 5, 3, 8, 5, 6] からインデックス 1, 2, 5 の要素を含む新しいリストを作成したいとします。私がしたことは次のとおりです。
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
それを行うより良い方法はありますか?c = a[b] のようなものですか?
インデックスを知って、指定されたリストからいくつかの要素を選択する必要があります。与えられたリスト [-2, 1, 5, 3, 8, 5, 6] からインデックス 1, 2, 5 の要素を含む新しいリストを作成したいとします。私がしたことは次のとおりです。
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [ a[i] for i in b]
それを行うより良い方法はありますか?c = a[b] のようなものですか?
提供された 5 つの回答の実行時間を比較する、基本的であまり広範囲ではないテスト:
def numpyIndexValues(a, b):
na = np.array(a)
nb = np.array(b)
out = list(na[nb])
return out
def mapIndexValues(a, b):
out = map(a.__getitem__, b)
return list(out)
def getIndexValues(a, b):
out = operator.itemgetter(*b)(a)
return out
def pythonLoopOverlap(a, b):
c = [ a[i] for i in b]
return c
multipleListItemValues = lambda searchList, ind: [searchList[i] for i in ind]
次の入力を使用します。
a = range(0, 10000000)
b = range(500, 500000)
単純な python ループはラムダ演算で 2 番目に速く、mapIndexValues と getIndexValues は numpy メソッドと一貫してかなり似ていましたが、リストを numpy 配列に変換した後は大幅に遅くなりました。最速。
numpyIndexValues -> time:1.38940598 (when converted the lists to numpy arrays)
numpyIndexValues -> time:0.0193445 (using numpy array instead of python list as input, and conversion code removed)
mapIndexValues -> time:0.06477512099999999
getIndexValues -> time:0.06391049500000001
multipleListItemValues -> time:0.043773591
pythonLoopOverlap -> time:0.043021754999999995
より簡単な方法は次のとおりです。
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [e for i, e in enumerate(a) if i in b]
私の答えは、numpy または python コレクションを使用しません。
要素を見つける簡単な方法は次のとおりです。
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
c = [i for i in a if i in b]
欠点: この方法は、大きなリストでは機能しない場合があります。大きなリストには numpy を使用することをお勧めします。
パイソン的な方法の種類:
c = [x for x in a if a.index(x) in b]