给定一个列表[“foo”、“bar”、“baz”]和列表“bar”中的一个项,如何获取其索引1?


当前回答

a = ["foo","bar","baz",'bar','any','much']

indexes = [index for index in range(len(a)) if a[index] == 'bar']

其他回答

大多数答案解释了如何找到一个索引,但如果项目多次出现在列表中,它们的方法不会返回多个索引。使用enumerate():

for i, j in enumerate(['foo', 'bar', 'baz']):
    if j == 'bar':
        print(i)

index()函数只返回第一次出现的情况,而enumerate()函数返回所有出现的情况。

作为列表理解:

[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar']

这里还有另一个使用itertools.count()的小解决方案(与enumerate方法几乎相同):

from itertools import izip as zip, count # izip for maximum efficiency
[i for i, j in zip(count(), ['foo', 'bar', 'baz']) if j == 'bar']

对于较大的列表,这比使用enumerate()更有效:

$ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ['foo', 'bar', 'baz']*500) if j == 'bar']"
10000 loops, best of 3: 174 usec per loop
$ python -m timeit "[i for i, j in enumerate(['foo', 'bar', 'baz']*500) if j == 'bar']"
10000 loops, best of 3: 196 usec per loop

获取列表中一个或多个(相同)项的所有出现次数和位置

使用enumerate(list),您可以存储第一个元素(n),当元素x等于您查找的值时,该元素是列表的索引。

>>> alist = ['foo', 'spam', 'egg', 'foo']
>>> foo_indexes = [n for n,x in enumerate(alist) if x=='foo']
>>> foo_indexes
[0, 3]
>>>

让我们让函数findindex

此函数将项和列表作为参数,并返回项在列表中的位置,就像我们之前看到的那样。

def indexlist(item2find, list_or_string):
  "Returns all indexes of an item in a list or a string"
  return [n for n,item in enumerate(list_or_string) if item==item2find]

print(indexlist("1", "010101010"))

输出


[1, 3, 5, 7]

易于理解的

for n, i in enumerate([1, 2, 3, 4, 1]):
    if i == 1:
        print(n)

输出:

0
4

我发现这两种解决方案更好,我自己尝试过

>>> expences = [2200, 2350, 2600, 2130, 2190]
>>> 2000 in expences
False
>>> expences.index(2200)
0
>>> expences.index(2350)
1
>>> index = expences.index(2350)
>>> expences[index]
2350

>>> try:
...     print(expences.index(2100))
... except ValueError as e:
...     print(e)
... 
2100 is not in list
>>> 


python中的一个简单解决方案:

li1=["foo","bar","baz"]
for i in range(len(li1)):
     if li1[i]=="bar":
          print(i)

列表元素的数据类型无关紧要。只需将“bar”替换为您要查找的元素。我们还可以为此编写一个函数:

def indexfinder(element,lis):
    for i in range(len(lis)):
        if lis[i]==element:
            return i
text = ["foo", "bar", "baz"]
target = "bar"

[index for index, value in enumerate(text) if value == target]

对于一个小的元素列表,这会很好。但是,如果列表包含大量元素,最好应用二进制运行时复杂度为O(logn)的搜索.