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


当前回答

查找列表L中项目x的索引:

idx = L.index(x) if (x in L) else -1

其他回答

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

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

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

我很感激,所以枚举到底做什么?。这帮助我理解了。

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

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

在查找列表中项目的索引时,列表理解将是获得紧凑实现的最佳选择。

a_list = ["a", "b", "a"]
print([index for (index , item) in enumerate(a_list) if item == "a"])

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

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