查找包含在Python中的列表的项的索引。

时间:2022-08-22 13:46:35

For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?

对于list ["foo"、"bar"、"baz"]和list "bar"中的一个项,最干净的方法是用Python得到它的索引(1)?

23 个解决方案

#1


3082  

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

Reference: Data Structures > More on Lists

数据结构>更多的在列表上。

#2


759  

One thing that is really helpful in learning Python is to use the interactive help function:

在学习Python时,有一点非常有用,那就是使用交互式帮助函数:

>>> help(["foo", "bar", "baz"])
Help on list object:

class list(object)
 ...

 |
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value
 |

which will often lead you to the method you are looking for.

这通常会引导你找到你想要的方法。

#3


431  

The majority of answers explain how to find a single index, but their methods do not return multiple indexes if the item is in the list multiple times. Use enumerate():

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

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

The index() function only returns the first occurrence, while enumerate() returns all occurrences.

函数只返回第一个事件,枚举()返回所有发生的事件。

As a list comprehension:

作为一个列表理解:

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

Here's also another small solution with itertools.count() (which is pretty much the same approach as enumerate):

这里还有一个带有itertools.count()的小解决方案(它几乎和枚举一样):

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

This is more efficient for larger lists than using enumerate():

对于较大的列表,这比使用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

#4


116  

To get all indexes:

所有索引:

 indexes = [i for i,x in enumerate(xs) if x == 'foo']

#5


104  

index() returns the first index of value!

index()返回值的第一个索引!

| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value

(…)| |指数L。索引(值,[启动,[停止]])->整数——返回值的第一个索引。

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"])

#6


64  

A problem will arise if the element is not in the list. This function handles the issue:

如果元素不在列表中,就会出现问题。这个函数处理这个问题:

# 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

#7


51  

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

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

#8


38  

You have to set a condition to check if the element you're searching is in the list

您必须设置一个条件来检查您正在搜索的元素是否在列表中。

if 'your_element' in mylist:
    print mylist.index('your_element')
else:
    print None

#9


34  

All of the proposed functions here reproduce inherent language behavior but obscure what's going on.

这里所提出的所有功能都是为了再现固有的语言行为,但却不清楚发生了什么。

[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

Why write a function with exception handling if the language provides the methods to do what you want itself?

如果语言提供了您想要的方法,为什么还要编写异常处理函数呢?

#10


27  

If you want all indexes, then you can use numpy:

如果您想要所有的索引,那么您可以使用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),)

It is clear, readable solution.

它是清晰易读的解决方案。

#11


19  

Finding the index of an item given a list containing it in Python

For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?

对于list ["foo"、"bar"、"baz"]和list "bar"中的一个项,最干净的方法是用Python得到它的索引(1)?

Well, sure, there's the index method, which returns the index of the first occurrence:

当然,这里有索引方法,它返回第一个事件的索引:

>>> l = ["foo", "bar", "baz"]
>>> l.index('bar')
1

There are a couple of issues with this method:

这个方法有几个问题:

  • if the value isn't in the list, you'll get a ValueError
  • 如果该值不在列表中,您将得到一个ValueError。
  • if more than one of the value is in the list, you only get the index for the first one
  • 如果超过一个值在列表中,那么您只会得到第一个值的索引。

No values

If the value could be missing, you need to catch the ValueError.

如果该值可能丢失,您需要捕获ValueError。

You can do so with a reusable definition like this:

您可以使用这样的可重用定义来实现:

def index(a_list, value):
    try:
        return a_list.index(value)
    except ValueError:
        return None

And use it like this:

然后像这样使用:

>>> print(index(l, 'quux'))
None
>>> print(index(l, 'bar'))
1

And the downside of this is that you will probably have a check for if the returned value is or is not None:

它的缺点是,你可能会检查返回值是否为零

result = index(a_list, value)
if result is not None:
    do_something(result)

More than one value in the list

If you could have more occurrences, you'll not get complete information with list.index:

如果您有更多的事件发生,您将无法获得列表的完整信息。

>>> l.append('bar')
>>> l
['foo', 'bar', 'baz', 'bar']
>>> l.index('bar')              # nothing at index 3?
1

You might enumerate into a list comprehension the indexes:

您可以将索引枚举到一个列表中:

>>> [index for index, v in enumerate(l) if v == 'bar']
[1, 3]
>>> [index for index, v in enumerate(l) if v == 'boink']
[]

If you have no occurrences, you can check for that with boolean check of the result, or just do nothing if you loop over the results:

如果您没有出现任何事件,您可以用boolean检查结果来检查,或者如果您对结果进行循环,就什么也不做:

indexes = [index for index, v in enumerate(l) if v == 'boink']
for index in indexes:
    do_something(index)

Better data munging with pandas

If you have pandas, you can easily get this information with a Series object:

如果你有熊猫,你可以很容易地得到这个信息和一个系列的对象:

>>> import pandas as pd
>>> series = pd.Series(l)
>>> series
0    foo
1    bar
2    baz
3    bar
dtype: object

A comparison check will return a series of booleans:

比较检查将返回一系列布尔值:

>>> series == 'bar'
0    False
1     True
2    False
3     True
dtype: bool

Pass that series of booleans to the series via subscript notation, and you get just the matching members:

通过下标符号传递一系列的布尔值,你只得到匹配的成员:

>>> series[series == 'bar']
1    bar
3    bar
dtype: object

If you want just the indexes, the index attribute returns a series of integers:

如果您只想要索引,则索引属性返回一系列整数:

>>> series[series == 'bar'].index
Int64Index([1, 3], dtype='int64')

And if you want them in a list or tuple, just pass them to the constructor:

如果您想要它们在列表或tuple中,请将它们传递给构造函数:

>>> list(series[series == 'bar'].index)
[1, 3]

Yes, you could use a list comprehension with enumerate too, but that's just not as elegant, in my opinion - you're doing tests for equality in Python, instead of letting builtin code written in C handle it:

是的,你也可以用列表理解来列举,但这并不像我认为的那样优雅,你在用Python做测试,而不是让用C写的内置代码来处理它:

>>> [i for i, value in enumerate(l) if value == 'bar']
[1, 3]

Is this an XY problem?

The XY problem is asking about your attempted solution rather than your actual problem.

XY问题是关于你的尝试解决方案而不是你的实际问题。

Why do you think you need the index given an element in a list?

为什么您认为您需要在列表中给定一个元素的索引?

If you already know the value, why do you care where it is in a list?

如果你已经知道了这个值,为什么要关心它在列表中的位置呢?

If the value isn't there, catching the ValueError is rather verbose - and I prefer to avoid that.

如果没有这个值,那么捕获ValueError是相当冗长的——我宁愿避免这一点。

I'm usually iterating over the list anyways, so I'll usually keep a pointer to any interesting information, getting the index with enumerate.

我通常会在列表上进行迭代,所以我通常会保留一个指向任何有趣信息的指针,以枚举列表来获取索引。

If you're munging data, you should probably be using pandas - which has far more elegant tools than the pure Python workarounds I've shown.

如果你想要数据,你应该使用熊猫——它比我所展示的纯Python工作区要优雅得多。

I do not recall needing list.index, myself. However, I have looked through the Python standard library, and I see some excellent uses for it.

我不记得需要清单。指数,我自己。但是,我已经浏览了Python标准库,并看到了一些优秀的用途。

There are many, many uses for it in idlelib, for GUI and text parsing.

在idlelib中有许多用于GUI和文本解析的用法。

The keyword module uses it to find comment markers in the module to automatically regenerate the list of keywords in it via metaprogramming.

关键字模块使用它在模块中找到注释标记,通过元编程自动生成关键字列表。

In Lib/mailbox.py it seems to be using it like an ordered mapping:

在Lib /邮箱。它看起来像一个有序的映射:

key_list[key_list.index(old)] = new

and

del key_list[key_list.index(key)]

In Lib/http/cookiejar.py, seems to be used to get the next month:

在Lib / http / cookiejar。py,似乎是用来下个月的:

mon = MONTHS_LOWER.index(mon.lower())+1

In Lib/tarfile.py similar to distutils to get a slice up to an item:

在Lib / tarfile。类似于distutils,它可以得到一个项目的切片:

members = members[:members.index(tarinfo)]

In Lib/pickletools.py:

在Lib / pickletools.py:

numtopop = before.index(markobject)

What these usages seem to have in common is that they seem to operate on lists of constrained sizes (important because of O(n) lookup time for list.index), and they're mostly used in parsing (and UI in the case of Idle).

这些用法似乎有一个共同之处,那就是它们似乎是在限制大小的列表上操作(重要的是,因为O(n)查找时间为list.index),而且它们主要用于解析(以及在空闲时的UI)。

While there are use-cases for it, they are fairly uncommon. If you find yourself looking for this answer, ask yourself if what you're doing is the most direct usage of the tools provided by the language for your use-case.

虽然有用例,但它们相当少见。如果你发现自己在寻找这个答案,问问你自己,你所做的是最直接地使用语言为你的用例提供的工具。

#12


17  

all indexes with zip function

所有索引具有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')

#13


15  

Simply you can go with

简单地说,你可以一起去。

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

res = [[x[0] for x in a].index(y) for y in b]

#14


13  

Another option

另一个选择

>>> 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]
>>> 

#15


13  

A variant on the answer from FMc and user7177 will give a dict that can return all indices for any entry:

FMc和user7177的答案的一个变体将给出一个命令,它可以返回任何条目的所有索引:

>>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
>>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
>>> l['foo']
[0, 5]
>>> l ['much']
[6]
>>> l
{'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
>>> 

You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called.

您还可以将其作为一个一行来获取单个条目的所有索引。虽然我确实使用set(a)来减少被调用的次数,但是没有对效率的保证。

#16


10  

And now, for something completely different...

... like confirming the existence of the item before getting the index. The nice thing about this approach is the function always returns a list of indices -- even if it is an empty list. It works with strings as well.

…比如在得到索引之前确认条目的存在。这种方法的好处是,函数总是返回一个索引列表——即使它是一个空列表。它也适用于字符串。

def indices(l, val):
    """Always returns a list containing the indices of val in the_list"""
    retval = []
    last = 0
    while val in l[last:]:
            i = l[last:].index(val)
            retval.append(last + i)
            last += i + 1   
    return retval

l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

When pasted into an interactive python window:

当粘贴到交互式python窗口时:

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(the_list, val):
...     """Always returns a list containing the indices of val in the_list"""
...     retval = []
...     last = 0
...     while val in the_list[last:]:
...             i = the_list[last:].index(val)
...             retval.append(last + i)
...             last += i + 1   
...     return retval
... 
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>> 

#17


10  

This solution is not as powerful as others, but if you're a beginner and only know about forloops it's still possible to find the first index of an item while avoiding the ValueError:

这个解决方案没有其他的解决方案那么强大,但是如果您是一个初学者,并且只知道for循环,那么在避免ValueError的同时,仍然可以找到一个项目的第一个索引:

def find_element(p,t):
    i = 0
    for e in p:
        if e == t:
            return i
        else:
            i +=1
    return -1

#18


9  

Getting all the occurrences and the position of one or more (identical) items in a list

With enumerate(alist) you can store the first element (n) that is the index of the list when the element x is equal to what you look for.

通过枚举(alist),您可以存储第一个元素(n),当元素x等于您所寻找的元素时,它是列表的索引。

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

Let's make our Function findindex

This function takes the item and the list as arg and return the position of the item in the liste, like we saw before.

这个函数将项目和列表作为arg,并返回liste中项目的位置,就像我们之前看到的那样。

def findindex(item2find,listOrString):
  "Search indexes of an item (arg.1) contained in a list or a string (arg.2)"
  return [n for n,item in enumerate(listOrString) if item==item2find]

indexes1 = findindex("1","010101010")
print(indexes1)

output

输出


[1, 3, 5, 7]

#19


5  

name ="bar"
list = [["foo", 1], ["bar", 2], ["baz", 3]]
new_list=[]
for item in list:
    new_list.append(item[0])
print(new_list)
try:
    location= new_list.index(name)
except:
    location=-1
print (location)

This accounts for if the string is not in the list too, if it isn't in the list then location = -1

如果字符串不在列表中,那么这个帐户就会出现,如果它不在列表中,那么location = -1。

#20


4  

Since Python lists are zero-based,we can use the zip built-in function as follows :

由于Python列表是从零开始的,所以我们可以使用zip内置函数如下:

>>> [i for i,j in zip(range(len(haystack)),haystack) if j == 'needle' ] 

where "haystack" is the list in question and "needle" is the item to look for.

“干草堆”是问题列表,“针”是要寻找的东西。

(Note : Here we are iterating using i to get the indexes but if we need rather to focus on the items we can switch to j)

(注意:这里我们正在迭代使用i来获取索引,但是如果我们需要将焦点集中在可以切换到j的项上)

#21


2  

Python index() method throws an error if the item was not found, which sucks!

如果没有找到条目,Python index()方法会抛出一个错误,这很糟糕!

So instead you can make it similar to the indexOf() function of Javascript which returns -1 if the item was not found:

因此,您可以使它类似于Javascript的indexOf()函数,如果未找到该项,则返回-1:

    try: 
        index = array.index('search_keyword')
    except ValueError:
        index = -1

#22


1  

For those caming from another language like me, maybe with a simple loop it's easier to understand and use it:

对于像我这样的另一种语言的人来说,也许用一个简单的循环就更容易理解和使用它:

mylist = ["foo", "bar", "baz", "bar"]
newlist = enumerate(mylist)
for index, item in newlist:
  if item == "bar":
    print(index, item)

Thankfull for https://www.codecademy.com/en/forum_questions/5087f2d786a27b02000041a9, that helped me to understand.

感谢https://www.codecademy.com/en/forum_questions/5087f2d786a27b02000041a9,帮助我理解。

#23


1  

There is a more functional answer to this.

有一个更实用的答案。

list(filter(lambda x: x[1]=="bar",enumerate(["foo", "bar", "baz", "bar", "baz", "bar", "a", "b", "c"])))

more generic form:

更一般的形式:

def get_index_of(lst, element):
    return list(map(lambda x: x[0],\
       (list(filter(lambda x: x[1]==element, enumerate(lst))))))

#1


3082  

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

Reference: Data Structures > More on Lists

数据结构>更多的在列表上。

#2


759  

One thing that is really helpful in learning Python is to use the interactive help function:

在学习Python时,有一点非常有用,那就是使用交互式帮助函数:

>>> help(["foo", "bar", "baz"])
Help on list object:

class list(object)
 ...

 |
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value
 |

which will often lead you to the method you are looking for.

这通常会引导你找到你想要的方法。

#3


431  

The majority of answers explain how to find a single index, but their methods do not return multiple indexes if the item is in the list multiple times. Use enumerate():

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

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

The index() function only returns the first occurrence, while enumerate() returns all occurrences.

函数只返回第一个事件,枚举()返回所有发生的事件。

As a list comprehension:

作为一个列表理解:

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

Here's also another small solution with itertools.count() (which is pretty much the same approach as enumerate):

这里还有一个带有itertools.count()的小解决方案(它几乎和枚举一样):

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

This is more efficient for larger lists than using enumerate():

对于较大的列表,这比使用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

#4


116  

To get all indexes:

所有索引:

 indexes = [i for i,x in enumerate(xs) if x == 'foo']

#5


104  

index() returns the first index of value!

index()返回值的第一个索引!

| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value

(…)| |指数L。索引(值,[启动,[停止]])->整数——返回值的第一个索引。

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"])

#6


64  

A problem will arise if the element is not in the list. This function handles the issue:

如果元素不在列表中,就会出现问题。这个函数处理这个问题:

# 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

#7


51  

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

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

#8


38  

You have to set a condition to check if the element you're searching is in the list

您必须设置一个条件来检查您正在搜索的元素是否在列表中。

if 'your_element' in mylist:
    print mylist.index('your_element')
else:
    print None

#9


34  

All of the proposed functions here reproduce inherent language behavior but obscure what's going on.

这里所提出的所有功能都是为了再现固有的语言行为,但却不清楚发生了什么。

[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

Why write a function with exception handling if the language provides the methods to do what you want itself?

如果语言提供了您想要的方法,为什么还要编写异常处理函数呢?

#10


27  

If you want all indexes, then you can use numpy:

如果您想要所有的索引,那么您可以使用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),)

It is clear, readable solution.

它是清晰易读的解决方案。

#11


19  

Finding the index of an item given a list containing it in Python

For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?

对于list ["foo"、"bar"、"baz"]和list "bar"中的一个项,最干净的方法是用Python得到它的索引(1)?

Well, sure, there's the index method, which returns the index of the first occurrence:

当然,这里有索引方法,它返回第一个事件的索引:

>>> l = ["foo", "bar", "baz"]
>>> l.index('bar')
1

There are a couple of issues with this method:

这个方法有几个问题:

  • if the value isn't in the list, you'll get a ValueError
  • 如果该值不在列表中,您将得到一个ValueError。
  • if more than one of the value is in the list, you only get the index for the first one
  • 如果超过一个值在列表中,那么您只会得到第一个值的索引。

No values

If the value could be missing, you need to catch the ValueError.

如果该值可能丢失,您需要捕获ValueError。

You can do so with a reusable definition like this:

您可以使用这样的可重用定义来实现:

def index(a_list, value):
    try:
        return a_list.index(value)
    except ValueError:
        return None

And use it like this:

然后像这样使用:

>>> print(index(l, 'quux'))
None
>>> print(index(l, 'bar'))
1

And the downside of this is that you will probably have a check for if the returned value is or is not None:

它的缺点是,你可能会检查返回值是否为零

result = index(a_list, value)
if result is not None:
    do_something(result)

More than one value in the list

If you could have more occurrences, you'll not get complete information with list.index:

如果您有更多的事件发生,您将无法获得列表的完整信息。

>>> l.append('bar')
>>> l
['foo', 'bar', 'baz', 'bar']
>>> l.index('bar')              # nothing at index 3?
1

You might enumerate into a list comprehension the indexes:

您可以将索引枚举到一个列表中:

>>> [index for index, v in enumerate(l) if v == 'bar']
[1, 3]
>>> [index for index, v in enumerate(l) if v == 'boink']
[]

If you have no occurrences, you can check for that with boolean check of the result, or just do nothing if you loop over the results:

如果您没有出现任何事件,您可以用boolean检查结果来检查,或者如果您对结果进行循环,就什么也不做:

indexes = [index for index, v in enumerate(l) if v == 'boink']
for index in indexes:
    do_something(index)

Better data munging with pandas

If you have pandas, you can easily get this information with a Series object:

如果你有熊猫,你可以很容易地得到这个信息和一个系列的对象:

>>> import pandas as pd
>>> series = pd.Series(l)
>>> series
0    foo
1    bar
2    baz
3    bar
dtype: object

A comparison check will return a series of booleans:

比较检查将返回一系列布尔值:

>>> series == 'bar'
0    False
1     True
2    False
3     True
dtype: bool

Pass that series of booleans to the series via subscript notation, and you get just the matching members:

通过下标符号传递一系列的布尔值,你只得到匹配的成员:

>>> series[series == 'bar']
1    bar
3    bar
dtype: object

If you want just the indexes, the index attribute returns a series of integers:

如果您只想要索引,则索引属性返回一系列整数:

>>> series[series == 'bar'].index
Int64Index([1, 3], dtype='int64')

And if you want them in a list or tuple, just pass them to the constructor:

如果您想要它们在列表或tuple中,请将它们传递给构造函数:

>>> list(series[series == 'bar'].index)
[1, 3]

Yes, you could use a list comprehension with enumerate too, but that's just not as elegant, in my opinion - you're doing tests for equality in Python, instead of letting builtin code written in C handle it:

是的,你也可以用列表理解来列举,但这并不像我认为的那样优雅,你在用Python做测试,而不是让用C写的内置代码来处理它:

>>> [i for i, value in enumerate(l) if value == 'bar']
[1, 3]

Is this an XY problem?

The XY problem is asking about your attempted solution rather than your actual problem.

XY问题是关于你的尝试解决方案而不是你的实际问题。

Why do you think you need the index given an element in a list?

为什么您认为您需要在列表中给定一个元素的索引?

If you already know the value, why do you care where it is in a list?

如果你已经知道了这个值,为什么要关心它在列表中的位置呢?

If the value isn't there, catching the ValueError is rather verbose - and I prefer to avoid that.

如果没有这个值,那么捕获ValueError是相当冗长的——我宁愿避免这一点。

I'm usually iterating over the list anyways, so I'll usually keep a pointer to any interesting information, getting the index with enumerate.

我通常会在列表上进行迭代,所以我通常会保留一个指向任何有趣信息的指针,以枚举列表来获取索引。

If you're munging data, you should probably be using pandas - which has far more elegant tools than the pure Python workarounds I've shown.

如果你想要数据,你应该使用熊猫——它比我所展示的纯Python工作区要优雅得多。

I do not recall needing list.index, myself. However, I have looked through the Python standard library, and I see some excellent uses for it.

我不记得需要清单。指数,我自己。但是,我已经浏览了Python标准库,并看到了一些优秀的用途。

There are many, many uses for it in idlelib, for GUI and text parsing.

在idlelib中有许多用于GUI和文本解析的用法。

The keyword module uses it to find comment markers in the module to automatically regenerate the list of keywords in it via metaprogramming.

关键字模块使用它在模块中找到注释标记,通过元编程自动生成关键字列表。

In Lib/mailbox.py it seems to be using it like an ordered mapping:

在Lib /邮箱。它看起来像一个有序的映射:

key_list[key_list.index(old)] = new

and

del key_list[key_list.index(key)]

In Lib/http/cookiejar.py, seems to be used to get the next month:

在Lib / http / cookiejar。py,似乎是用来下个月的:

mon = MONTHS_LOWER.index(mon.lower())+1

In Lib/tarfile.py similar to distutils to get a slice up to an item:

在Lib / tarfile。类似于distutils,它可以得到一个项目的切片:

members = members[:members.index(tarinfo)]

In Lib/pickletools.py:

在Lib / pickletools.py:

numtopop = before.index(markobject)

What these usages seem to have in common is that they seem to operate on lists of constrained sizes (important because of O(n) lookup time for list.index), and they're mostly used in parsing (and UI in the case of Idle).

这些用法似乎有一个共同之处,那就是它们似乎是在限制大小的列表上操作(重要的是,因为O(n)查找时间为list.index),而且它们主要用于解析(以及在空闲时的UI)。

While there are use-cases for it, they are fairly uncommon. If you find yourself looking for this answer, ask yourself if what you're doing is the most direct usage of the tools provided by the language for your use-case.

虽然有用例,但它们相当少见。如果你发现自己在寻找这个答案,问问你自己,你所做的是最直接地使用语言为你的用例提供的工具。

#12


17  

all indexes with zip function

所有索引具有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')

#13


15  

Simply you can go with

简单地说,你可以一起去。

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

res = [[x[0] for x in a].index(y) for y in b]

#14


13  

Another option

另一个选择

>>> 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]
>>> 

#15


13  

A variant on the answer from FMc and user7177 will give a dict that can return all indices for any entry:

FMc和user7177的答案的一个变体将给出一个命令,它可以返回任何条目的所有索引:

>>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
>>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
>>> l['foo']
[0, 5]
>>> l ['much']
[6]
>>> l
{'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
>>> 

You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called.

您还可以将其作为一个一行来获取单个条目的所有索引。虽然我确实使用set(a)来减少被调用的次数,但是没有对效率的保证。

#16


10  

And now, for something completely different...

... like confirming the existence of the item before getting the index. The nice thing about this approach is the function always returns a list of indices -- even if it is an empty list. It works with strings as well.

…比如在得到索引之前确认条目的存在。这种方法的好处是,函数总是返回一个索引列表——即使它是一个空列表。它也适用于字符串。

def indices(l, val):
    """Always returns a list containing the indices of val in the_list"""
    retval = []
    last = 0
    while val in l[last:]:
            i = l[last:].index(val)
            retval.append(last + i)
            last += i + 1   
    return retval

l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

When pasted into an interactive python window:

当粘贴到交互式python窗口时:

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(the_list, val):
...     """Always returns a list containing the indices of val in the_list"""
...     retval = []
...     last = 0
...     while val in the_list[last:]:
...             i = the_list[last:].index(val)
...             retval.append(last + i)
...             last += i + 1   
...     return retval
... 
>>> l = ['bar','foo','bar','baz','bar','bar']
>>> q = 'bar'
>>> print indices(l,q)
[0, 2, 4, 5]
>>> print indices(l,'bat')
[]
>>> print indices('abcdaababb','a')
[0, 4, 5, 7]
>>> 

#17


10  

This solution is not as powerful as others, but if you're a beginner and only know about forloops it's still possible to find the first index of an item while avoiding the ValueError:

这个解决方案没有其他的解决方案那么强大,但是如果您是一个初学者,并且只知道for循环,那么在避免ValueError的同时,仍然可以找到一个项目的第一个索引:

def find_element(p,t):
    i = 0
    for e in p:
        if e == t:
            return i
        else:
            i +=1
    return -1

#18


9  

Getting all the occurrences and the position of one or more (identical) items in a list

With enumerate(alist) you can store the first element (n) that is the index of the list when the element x is equal to what you look for.

通过枚举(alist),您可以存储第一个元素(n),当元素x等于您所寻找的元素时,它是列表的索引。

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

Let's make our Function findindex

This function takes the item and the list as arg and return the position of the item in the liste, like we saw before.

这个函数将项目和列表作为arg,并返回liste中项目的位置,就像我们之前看到的那样。

def findindex(item2find,listOrString):
  "Search indexes of an item (arg.1) contained in a list or a string (arg.2)"
  return [n for n,item in enumerate(listOrString) if item==item2find]

indexes1 = findindex("1","010101010")
print(indexes1)

output

输出


[1, 3, 5, 7]

#19


5  

name ="bar"
list = [["foo", 1], ["bar", 2], ["baz", 3]]
new_list=[]
for item in list:
    new_list.append(item[0])
print(new_list)
try:
    location= new_list.index(name)
except:
    location=-1
print (location)

This accounts for if the string is not in the list too, if it isn't in the list then location = -1

如果字符串不在列表中,那么这个帐户就会出现,如果它不在列表中,那么location = -1。

#20


4  

Since Python lists are zero-based,we can use the zip built-in function as follows :

由于Python列表是从零开始的,所以我们可以使用zip内置函数如下:

>>> [i for i,j in zip(range(len(haystack)),haystack) if j == 'needle' ] 

where "haystack" is the list in question and "needle" is the item to look for.

“干草堆”是问题列表,“针”是要寻找的东西。

(Note : Here we are iterating using i to get the indexes but if we need rather to focus on the items we can switch to j)

(注意:这里我们正在迭代使用i来获取索引,但是如果我们需要将焦点集中在可以切换到j的项上)

#21


2  

Python index() method throws an error if the item was not found, which sucks!

如果没有找到条目,Python index()方法会抛出一个错误,这很糟糕!

So instead you can make it similar to the indexOf() function of Javascript which returns -1 if the item was not found:

因此,您可以使它类似于Javascript的indexOf()函数,如果未找到该项,则返回-1:

    try: 
        index = array.index('search_keyword')
    except ValueError:
        index = -1

#22


1  

For those caming from another language like me, maybe with a simple loop it's easier to understand and use it:

对于像我这样的另一种语言的人来说,也许用一个简单的循环就更容易理解和使用它:

mylist = ["foo", "bar", "baz", "bar"]
newlist = enumerate(mylist)
for index, item in newlist:
  if item == "bar":
    print(index, item)

Thankfull for https://www.codecademy.com/en/forum_questions/5087f2d786a27b02000041a9, that helped me to understand.

感谢https://www.codecademy.com/en/forum_questions/5087f2d786a27b02000041a9,帮助我理解。

#23


1  

There is a more functional answer to this.

有一个更实用的答案。

list(filter(lambda x: x[1]=="bar",enumerate(["foo", "bar", "baz", "bar", "baz", "bar", "a", "b", "c"])))

more generic form:

更一般的形式:

def get_index_of(lst, element):
    return list(map(lambda x: x[0],\
       (list(filter(lambda x: x[1]==element, enumerate(lst))))))