对于列表["foo", "bar", "baz"]和列表"bar" ,如何在Python中获取其索引(1)?


#1楼

a = ["foo","bar","baz",'bar','any','much']indexes = [index for index in range(len(a)) if a[index] == 'bar']

#2楼

如果该元素不在列表中,则会出现问题。 此函数可解决此问题:

# if element is found it returns index of element else returns Nonedef find_element_in_list(element, list_element):try:index_element = list_element.index(element)return index_elementexcept ValueError:return None

#3楼

此处提出的所有功能均会重现固有的语言行为,但会掩盖正在发生的事情。

[i for i in range(len(mylist)) if mylist[i]==myterm]  # get the indices[each for each in mylist if each==myterm]             # get the itemsmylist.index(myterm) if myterm in mylist else None    # get the first index and fail quietly

如果该语言提供了执行所需功能的方法,为什么还要编写具有异常处理功能的函数?


#4楼

只需您可以选择

a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']res = [[x[0] for x in a].index(y) for y in b]

#5楼

另外一个选项

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

#6楼

大多数答案都说明了如何查找单个索引 ,但是如果该项在列表中多次,则它们的方法不会返回多个索引。 使用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()另一个小解决方案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']

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

#7楼

要获取所有索引:

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

#8楼

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

参考: 数据结构>列表中的更多内容

注意事项

请注意,虽然这也许是回答, 因为问的问题最彻底的方法, index是一个相当薄弱的组件list API,我不记得我最后一次使用它的愤怒。 在评论中已向我指出,由于此答案被大量引用,因此应使其更完整。 有关list.index一些警告。 可能值得一开始看看它的文档字符串:

>>> print(list.index.__doc__)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.

列表长度的线性时间复杂度

index调用按顺序检查列表中的每个元素,直到找到匹配项。 如果您的列表很长,并且您大概不知道它在列表中的哪个位置,则此搜索可能会成为瓶颈。 在这种情况下,您应该考虑使用其他数据结构。 请注意,如果您大致知道在哪里找到匹配项,则可以给index一个提示。 例如,在此代码段中, l.index(999_999, 999_990, 1_000_000)比直线l.index(999_999)快大约五个数量级,因为前者只需搜索10个条目,而后者则搜索一百万个:

>>> 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/except块中,该块捕获ValueError (可能更快,至少在要搜索的列表很长且通常存在该项的情况下)。

#9楼

学习Python真正有用的一件事是使用交互式帮助功能:

>>> help(["foo", "bar", "baz"])
Help on list object:class list(object)...||  index(...)|      L.index(value, [start, [stop]]) -> integer -- return first index of value|

这通常会引导您找到所需的方法。


#10楼

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

您也可以将其用作单个衬纸,以获取单个条目的所有索引。 尽管我确实使用set(a)减少了调用lambda的次数,但是并不能保证效率。


#11楼

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

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

#12楼

而现在,对于完全不同的东西...

...就像在获取索引之前确认项目的存在。 这种方法的好处是,该函数始终返回一个索引列表-即使它是一个空列表。 它也适用于字符串。

def indices(l, val):"""Always returns a list containing the indices of val in the_list"""retval = []last = 0while val in l[last:]:i = l[last:].index(val)retval.append(last + i)last += i + 1   return retvall = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

当粘贴到交互式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]
>>>

更新资料

经过一年的低沉的python开发,我对最初的答案感到有些尴尬,因此要想保持纪录,肯定可以使用上面的代码; 然而, 地道的方式来获得相同的行为是使用列表理解,用枚举()函数一起。

像这样:

def indices(l, val):"""Always returns a list containing the indices of val in the_list"""return [index for index, value in enumerate(l) if value == val]l = ['bar','foo','bar','baz','bar','bar']
q = 'bar'
print indices(l,q)
print indices(l,'bat')
print indices('abcdaababb','a')

将其粘贴到交互式python窗口中时会产生:

Python 2.7.14 |Anaconda, Inc.| (default, Dec  7 2017, 11:07:58)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def indices(l, val):
...     """Always returns a list containing the indices of val in the_list"""
...     return [index for index, value in enumerate(l) if value == val]
...
>>> 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]
>>>

现在,在回顾了这个问题和所有答案之后,我意识到这正是FMc在他先前的答案中所建议的。 当我最初回答这个问题时,我什至没有看到那个答案,因为我不理解。 我希望我的详细示例能有助于理解。

如果上面的单行代码对您仍然没有意义,我强烈建议您使用Google“ python list comprehension”,花一些时间来熟悉一下自己。 它只是众多强大功能之一,使使用Python开发代码感到非常高兴。


#13楼

此解决方案不像其他解决方案那么强大,但是如果您是一个初学者,并且只了解for循环,仍然可以在避免ValueError的情况下找到项目的第一个索引:

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

#14楼

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)

这说明字符串是否也不在列表中,如果字符串也不在列表中,则location = -1


#15楼

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

#16楼

如果需要所有索引,则可以使用NumPy :

import numpy as nparray = [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),)

这是一个清晰易读的解决方案。


#17楼

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

使用enumerate(alist)可以存储第一个元素(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

#18楼

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

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

其中“ haystack”是有问题的列表,“ needle”是要查找的项目。

(注意:这里我们使用i进行迭代以获取索引,但是如果我们需要专注于项目,可以切换到j。)


#19楼

在Python中给定包含该项目的列表的情况下查找项目的索引

对于列表["foo", "bar", "baz"]和列表"bar"的项目,在Python中获取其索引(1)的最干净方法是什么?

好吧,可以肯定的是,这里有index方法,它返回第一次出现的索引:

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

此方法存在两个问题:

  • 如果该值不在列表中,则将出现ValueError
  • 如果列表中有多个值,则仅获取第一个的索引

没有值

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

您可以使用这样的可重用定义来执行此操作:

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

并像这样使用它:

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

缺点是您可能会检查返回的值is is not None:

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

列表中有多个值

如果可能出现更多次,您将无法通过list.index获得完整的信息:

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

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

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

如果没有出现,则可以通过布尔检查结果来进行检查,或者如果对结果进行循环,则什么也不做:

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

用熊猫更好地处理数据

如果您有熊猫,则可以通过Series对象轻松获得以下信息:

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

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

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

通过下标符号将该布尔值系列传递给该系列,您将只获得匹配的成员:

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

如果只需要索引,index属性将返回一系列整数:

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

而且,如果要将它们放在列表或元组中,只需将它们传递给构造函数即可:

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

是的,您也可以使用带有枚举的列表理解,但这在我看来并不那么优雅-您正在用Python进行相等性测试,而不是让用C编写的内置代码来处理它:

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

这是XY问题吗?

XY问题是在询问您尝试的解决方案,而不是您的实际问题。

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

如果您已经知道该值,为什么还要关心它在列表中的位置?

如果该值不存在,则捕获ValueError相当冗长-我希望避免这种情况。

无论如何,我通常都会遍历该列表,因此我通常会保留一个指向任何有趣信息的指针,并使用枚举获取索引。

如果您要处理数据,则可能应该使用pandas-它比我展示的纯Python解决方法具有更出色的工具。

我不记得自己需要list.index 。 但是,我浏览了Python标准库,并且看到了一些很好的用法。

idlelib在GUI和文本解析中有很多用途。

keyword模块使用它在模块中查找注释标记,以通过元编程自动重新生成其中的关键字列表。

在Lib / mailbox.py中,它似乎像有序映射一样在使用它:

key_list[key_list.index(old)] = new

del key_list[key_list.index(key)]

在Lib / http / cookiejar.py中,似乎用来获取下个月的内容:

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

在Lib / tarfile.py中,类似于distutils来获取最多一个项目的切片:

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

在Lib / pickletools.py中:

numtopop = before.index(markobject)

这些用法似乎有一个共同点,即它们似乎在受限大小的列表上运行(这很重要,因为list.index的O(n)查找时间很重要),并且它们通常用于解析(对于UI, list.index闲)。

尽管有用例,但这种情况很少见。 如果发现自己正在寻找该答案,请问自己是否正在使用的语言最直接地用于您的用例。


#20楼

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

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

我很感激, 那么枚举到底是做什么的? 。 那帮助我理解了。


#21楼

如果未找到该项目,Python index()方法将引发错误。 因此,可以改为使其类似于JavaScript的indexOf()函数,如果未找到该项,则返回-1

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

#22楼

有一个更实用的答案。

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

更通用的形式:

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

#23楼

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

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

#24楼

如果性能值得关注:

在众多答案中都提到list.index(item)方法的内置方法是O(n)算法。 如果您需要执行一次,那就很好。 但是,如果您需要多次访问元素的索引,则首先创建一个由项-索引对组成的字典(O(n)),然后每次需要时在O(1)处访问索引就更有意义了。它。

如果您确定列表中的项目不会重复,则可以轻松地进行以下操作:

myList = ["foo", "bar", "baz"]# Create the dictionary
myDict = dict((e,i) for i,e in enumerate(myList))# Lookup
myDict["bar"] # Returns 1
# myDict.get("blah") if you don't want an error to be raised if element not found.

如果您可能有重复的元素,并且需要返回其所有索引:

from collections import defaultdict as dd
myList = ["foo", "bar", "bar", "baz", "foo"]# Create the dictionary
myDict = dd(list)
for i,e in enumerate(myList):myDict[e].append(i)# Lookup
myDict["foo"] # Returns [0, 4]

#25楼

如@TerryA所示,许多答案都讨论了如何查找一个索引。

more_itertools是一个第三方库,具有用于在可迭代对象中定位多个索引的工具。

给定

import more_itertools as mititerable = ["foo", "bar", "baz", "ham", "foo", "bar", "baz"]

查找多个观测值的索引:

list(mit.locate(iterable, lambda x: x == "bar"))
# [1, 5]

测试多个项目:

list(mit.locate(iterable, lambda x: x in {"bar", "ham"}))
# [1, 3, 5]

另请参见more_itertools.locate更多选项。 通过> pip install more_itertools


#26楼

让我们将名称lst命名为您拥有的列表。 可以将列表lst转换为numpy array 。 并且,然后使用numpy.where获取列表中所选项目的索引。 以下是实现它的方法。

import numpy as nplst = ["foo", "bar", "baz"]  #lst: : 'list' data type
print np.where( np.array(lst) == 'bar')[0][0]>>> 1

#27楼

使用dictionary,其中首先处理列表,然后向其添加索引

from collections import defaultdictindex_dict = defaultdict(list)
word_list =  ['foo','bar','baz','bar','any', 'foo', 'much']for word_index in range(len(word_list)) :index_dict[word_list[word_index]].append(word_index)word_index_to_find = 'foo'
print(index_dict[word_index_to_find])# output :  [0, 5]

#28楼

为了防止ValueError,尽管类也可以工作,但您可以使函数实现此目的。

def findInList(List, item):try:return List.index(item)except ValueError:return -1

唯一的问题是,这可能会导致难以跟踪的错误。 其他数字也一样。
但是,如果返回的不是数字,则将其用作列表索引,并且无论如何都会不可避免地引发错误。

我认为,如果找不到该项目,就假定出了点问题,最好使用try except ,但是要使用自定义错误消息,这样就不会使调试变得更加困难,返回值也不会很重要:

# python 3.xclass itemNotFoundInListError(Exception): passdef findInList(List, item):try:return List.index(item)except ValueError:raise itemNotFoundInListError(f"List `{List}` does not contain `{item}.`")

#29楼

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

| 指数(...)
| L.index(value,[start,[stop]])->整数-返回值的第一个索引

def all_indices(value, qlist):indices = []idx = -1while True:try:idx = qlist.index(value, idx+1)indices.append(idx)except ValueError:breakreturn indicesall_indices("foo", ["foo","bar","baz","foo"])

在Python中给定包含该项目的列表的情况下查找项目的索引相关推荐

  1. Python中如何获得数组或者列表按大小排序后元素的索引列表

    使用 np.argsort 函数 import numpy as np a = np.array([10,40,30,50,25]) b = np.argsort(a)# 从小到大排序的元素的索引 p ...

  2. 如何在 Python 中以表格格式打印列表?

    在 Python 中,列表是一种常见的数据结构,用于存储和组织数据.当我们需要将列表的内容以表格形式展示时,可以通过特定的方法和技巧来实现.本文将详细介绍如何在 Python 中以表格格式打印列表,以 ...

  3. python中怎么比较两个列表-python中如何比较两个列表不同

    通过不断的测试发现,python实现高效快速比对两个列表的不同,可借助python集合set()提供的集合运算进行操作,此方式效率非常高. 而在java语言中,如下方法中方法1相比方法2(集合运算)的 ...

  4. python中怎么比较两个列表-python中如何比较两个列表

    cmp() 方法用于比较两个列表的元素. cmp()方法语法:cmp(list1, list2) 参数: list1 -- 比较的列表.list2 -- 比较的列表. 返回值: 如果比较的元素是同类型 ...

  5. lambda在python_在Python中使用lambda高效操作列表的教程

    介绍 lambda Python用于支持将函数赋值给变量的一个操作符 默认是返回的,所以不用再加return关键字,不然会报错 result = lambda x: x * x result(2) # ...

  6. python中求包含5的数_Python 内置函数 ( ) 可以返回列表、元组、字典、集合、字符串以及 range 对象中元素个数。_学小易找答案...

    [简答题]实例1:求两数相除的结果. 先后输入2个数据,计算第一个数除以第二个数的结果. 要求能够处理输入数据为非数字.除数为零.文件末尾EndOfFile 和用户使用Ctrl + C 命令终止程序等 ...

  7. python中def fun 定义函数列表_python函数

    # -*- coding:utf-8 -*- #yys #python 3.7.2 # 1.定义函数.调用函数 # 函数:组织好的.可重复使用的.用户实现单一或者关联功能的代码段. # 函数能够提高应 ...

  8. Python中字符串的截取,列表的截取

    字符串的截取 Python中的字符串用单引号 ' 或双引号 " 括起来,同时使用反斜杠 \ 转义特殊字符. 字符串的截取的语法格式如下: 变量[头下标:尾下标] 索引值以 0 为开始值,-1 ...

  9. python中的序列总结:列表,元组,字符串

    首先python中的序列有列表,元组,字符串. 列表List是python里面最基本的数据结构.序列中每个元素都是从索引(下标)从0开始,依次叠加. List操作的方法很多,只能熟悉基本常用的这个方法 ...

最新文章

  1. 记录CSS3 target伪类简介
  2. POJ 1989 贪心
  3. 类脑芯片怎么搞?三星哈佛:直接复制粘贴神经元 | Nature子刊
  4. CTO在企业技术创新中的作用和地位
  5. 从SAP Hybris下单,同步到S/4HANA,触发生产流程
  6. 如何在VMware8虚拟机里安装Xp GHOST系统 解决不能启动Xp系统方法
  7. 搜索时展示的是名字,传给后端的是id
  8. “资源添加到Web应用程序[]的缓存中,因为在清除过期缓存条目后可用空间仍不足 - 请考虑增加缓存的最大空间”
  9. 很有气势的语言openeim
  10. 数的划分(洛谷-P1025)
  11. 加密视频如何破解 如何解除机器码绑定的视频
  12. vb将excel数据导入mysql_使用VB将Excel导入到Sql中
  13. 应用回归分析第五版电子书_应用回归分析 R语言版_何晓群著_2017年
  14. 一个小小的flash
  15. 自动化测试的7个步骤
  16. Unity-黑暗之魂复刻-跳跃功能
  17. java计算机毕业设计银创科技有限公司人事信息系统源码+数据库+系统+lw文档+部署
  18. Chatbot是什么?chatbot平台有哪些?有什么AI chatbots推荐?SaleSmartly chatbot助力独立站运营
  19. python评价指标_[Python人工智能] 六.神经网络的评价指标、特征标准化和特征选择...
  20. ZDNS赋能创新型高等学府——清华大学深圳国际研究生院

热门文章

  1. scala学习笔记(1)
  2. 每日英语:Three Shows That Changed The Way Networks Think About Viewership
  3. JQuery入门 初级插件02
  4. c#利用反射+特性实现简单的实体映射数据库操作类(表与类的映射)
  5. day08.4-samba共享网盘服务
  6. python入门_老男孩_数据类型简介_int/bool/str转换_字符串索引和切片_字符串操作_day3...
  7. 静态代码块的执行顺序
  8. stm32中的延时函数
  9. 利用conda安装git
  10. window 右击菜单启动 nodejs app