3959

["foo", "bar", "baz"]listと list 内の項目が与えられた場合、Python で"bar"そのインデックス ( ) を取得するにはどうすればよいですか?1

4

39 に答える 39

5475
>>> ["foo", "bar", "baz"].index("bar")
1

リファレンス:データ構造 > リストの詳細

警告に従う

これはおそらく、尋ねられた質問に答える最もクリーンな方法ですindex、API のかなり弱いコンポーネントでありlist、最後に怒って使用したのはいつだったか思い出せません。コメントで、この回答は頻繁に参照されているため、より完全にする必要があると指摘されています。list.indexフォローに関するいくつかの注意事項。おそらく、最初にドキュメントを参照する価値があります。

list.index(x[, start[, end]])

値がxに等しい最初の項目のリスト内のゼロから始まるインデックスを返します。ValueErrorそのようなアイテムがない場合はaを発生させます。

オプションの引数startendは、スライス表記のように解釈され、検索をリストの特定のサブシーケンスに制限するために使用されます。返されるインデックスは、開始引数ではなく、完全なシーケンスの先頭を基準にして計算されます。

リストの長さの線形時間複雑度

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

アイテムがリストに存在しない可能性がある場合は、次のいずれかを行う必要があります

  1. 最初にitem in my_list(クリーンで読みやすいアプローチ)、または
  2. キャッチindexするブロックで呼び出しをラップします(少なくとも検索するリストが長く、アイテムが通常存在する場合は、おそらくより高速です)。try/exceptValueError
于 2008-10-07T01:40:49.213 に答える
972

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
 |

多くの場合、探している方法にたどり着きます。

于 2008-10-07T13:19:56.933 に答える
149

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"])
于 2011-08-30T09:40:54.867 に答える
98
a = ["foo","bar","baz",'bar','any','much']

indexes = [index for index in range(len(a)) if a[index] == 'bar']
于 2012-08-21T12:01:54.630 に答える
98

要素がリストにない場合、問題が発生します。この関数は問題を処理します:

# 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
于 2013-04-16T10:19:36.350 に答える
66

検索している要素がリストにあるかどうかを確認する条件を設定する必要があります

if 'your_element' in mylist:
    print mylist.index('your_element')
else:
    print None
于 2014-05-26T04:26:52.337 に答える
56

すべてのインデックスが必要な場合は、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),)

明確で読みやすいソリューションです。

于 2015-11-17T19:05:23.603 に答える
51

ここで提案されているすべての関数は、固有の言語の動作を再現しますが、何が起こっているのかわかりません。

[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

言語が自分でやりたいことを実行するメソッドを提供しているのに、なぜ例外処理を伴う関数を書くのでしょうか?

于 2013-05-16T16:45:29.667 に答える
24

関数を持つすべてのインデックス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')
于 2015-11-11T05:16:38.490 に答える
22

単にあなたが行くことができます

a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']

res = [[x[0] for x in a].index(y) for y in b]
于 2013-05-29T07:17:15.180 に答える
19

別のオプション

>>> 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]
>>> 
于 2013-05-29T19:17:21.037 に答える
6

比較対象の 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()]
于 2020-06-22T16:02:01.873 に答える
2

Python の特定の構造には、この問題を解決するために美しく機能する index メソッドが含まれています。

'oi tchau'.index('oi')     # 0
['oi','tchau'].index('oi') # 0
('oi','tchau').index('oi') # 0

参考文献:

リスト内

タプルで

文字列で

于 2021-12-29T18:49:45.980 に答える