["foo", "bar", "baz"]
listと list 内の項目が与えられた場合、Python で"bar"
そのインデックス ( ) を取得するにはどうすればよいですか?1
39 に答える
>>> ["foo", "bar", "baz"].index("bar")
1
リファレンス:データ構造 > リストの詳細
警告に従う
これはおそらく、尋ねられた質問に答える最もクリーンな方法ですがindex
、API のかなり弱いコンポーネントでありlist
、最後に怒って使用したのはいつだったか思い出せません。コメントで、この回答は頻繁に参照されているため、より完全にする必要があると指摘されています。list.index
フォローに関するいくつかの注意事項。おそらく、最初にドキュメントを参照する価値があります。
list.index(x[, start[, end]])
値がxに等しい最初の項目のリスト内のゼロから始まるインデックスを返します。
ValueError
そのようなアイテムがない場合はaを発生させます。オプションの引数startとendは、スライス表記のように解釈され、検索をリストの特定のサブシーケンスに制限するために使用されます。返されるインデックスは、開始引数ではなく、完全なシーケンスの先頭を基準にして計算されます。
リストの長さの線形時間複雑度
index
呼び出しは、一致が見つかるまで、リストのすべての要素を順番にチェックします。リストが長く、リスト内のどこで発生するかが大まかにわからない場合、この検索がボトルネックになる可能性があります。その場合、別のデータ構造を検討する必要があります。一致する場所を大まかに知っている場合はindex
、ヒントを与えることができます。たとえば、次のスニペットでl.index(999_999, 999_990, 1_000_000)
は、 straight よりもおよそ 5 桁高速ですl.index(999_999)
。なぜなら、前者は 10 エントリしか検索しなくてもよいのに対し、後者は 100 万を検索するからです。
>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
引数に最初に一致したインデックスのみを返します
への呼び出しindex
は、一致が見つかるまでリストを順番に検索し、そこで停止します。より多くの一致のインデックスが必要な場合は、リスト内包表記またはジェネレーター式を使用する必要があります。
>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2
以前は を使用していたほとんどの場所でindex
、現在はリスト内包表記またはジェネレーター式を使用しています。より一般化できるからです。に到達することを検討している場合はindex
、これらの優れた Python 機能をご覧ください。
要素がリストに存在しない場合にスローします
を呼び出すと、アイテムが存在しない場合にindex
結果が返されます。ValueError
>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
アイテムがリストに存在しない可能性がある場合は、次のいずれかを行う必要があります
- 最初に
item in my_list
(クリーンで読みやすいアプローチ)、または - キャッチ
index
するブロックで呼び出しをラップします(少なくとも検索するリストが長く、アイテムが通常存在する場合は、おそらくより高速です)。try/except
ValueError
Python の学習に非常に役立つことの 1 つは、インタラクティブなヘルプ機能を使用することです。
>>> help(["foo", "bar", "baz"])
Help on list object:
class list(object)
...
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value
|
多くの場合、探している方法にたどり着きます。
index()
値の最初のインデックスを返します!
| | インデックス(...)
| L.index(value, [start, [stop]]) -> integer -- 値の最初のインデックスを返す
def all_indices(value, qlist):
indices = []
idx = -1
while True:
try:
idx = qlist.index(value, idx+1)
indices.append(idx)
except ValueError:
break
return indices
all_indices("foo", ["foo","bar","baz","foo"])
a = ["foo","bar","baz",'bar','any','much']
indexes = [index for index in range(len(a)) if a[index] == 'bar']
要素がリストにない場合、問題が発生します。この関数は問題を処理します:
# if element is found it returns index of element else returns None
def find_element_in_list(element, list_element):
try:
index_element = list_element.index(element)
return index_element
except ValueError:
return None
検索している要素がリストにあるかどうかを確認する条件を設定する必要があります
if 'your_element' in mylist:
print mylist.index('your_element')
else:
print None
すべてのインデックスが必要な場合は、NumPyを使用できます。
import numpy as np
array = [1, 2, 1, 3, 4, 5, 1]
item = 1
np_array = np.array(array)
item_index = np.where(np_array==item)
print item_index
# Out: (array([0, 2, 6], dtype=int64),)
明確で読みやすいソリューションです。
ここで提案されているすべての関数は、固有の言語の動作を再現しますが、何が起こっているのかわかりません。
[i for i in range(len(mylist)) if mylist[i]==myterm] # get the indices
[each for each in mylist if each==myterm] # get the items
mylist.index(myterm) if myterm in mylist else None # get the first index and fail quietly
言語が自分でやりたいことを実行するメソッドを提供しているのに、なぜ例外処理を伴う関数を書くのでしょうか?
関数を持つすべてのインデックスzip
:
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print get_indexes(2, [1, 2, 3, 4, 5, 6, 3, 2, 3, 2])
print get_indexes('f', 'xsfhhttytffsafweef')
単にあなたが行くことができます
a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']
res = [[x[0] for x in a].index(y) for y in b]
別のオプション
>>> a = ['red', 'blue', 'green', 'red']
>>> b = 'red'
>>> offset = 0;
>>> indices = list()
>>> for i in range(a.count(b)):
... indices.append(a.index(b,offset))
... offset = indices[-1]+1
...
>>> indices
[0, 3]
>>>
比較対象の 1 つに対して
# Throws ValueError if nothing is found
some_list = ['foo', 'bar', 'baz'].index('baz')
# some_list == 2
カスタム述語
some_list = [item1, item2, item3]
# Throws StopIteration if nothing is found
# *unless* you provide a second parameter to `next`
index_of_value_you_like = next(
i for i, item in enumerate(some_list)
if item.matches_your_criteria())
述語によるすべてのアイテムのインデックスの検索
index_of_staff_members = [
i for i, user in enumerate(users)
if user.is_staff()]