>>> # A list comprehension gives a list of indices directly:>>> [i for i, e in enumerate([1, 2, 1]) if e == 1][0, 2]>>> # A generator comprehension gives us an iterable object...>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)>>> # which can be used in a `for` loop, or manually iterated with `next`:>>> next(g)0>>> next(g)2
如果只有一个匹配项,列表理解和生成器表达式技术仍然有效,并且更具通用性。
如果没有匹配,则引发异常
如上所述,如果搜索的值不在列表中,使用.index将引发异常:
>>> [1, 1].index(2)Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: 2 is not in list
如果这是一个问题,要么首先明确检查使用item in my_list,要么酌情使用try/except处理异常。
# 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_elementexcept ValueError:return None
[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
>>> 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]>>>
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
>>> 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]}>>>
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 + 1return retval
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.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "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]>>>
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 darwinType "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]>>>
>>> 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)
myList = ["foo", "bar", "baz"]
# Create the dictionarymyDict = dict((e,i) for i,e in enumerate(myList))
# LookupmyDict["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 ddmyList = ["foo", "bar", "bar", "baz", "foo"]
# Create the dictionarymyDict = dd(list)for i,e in enumerate(myList):myDict[e].append(i)
# LookupmyDict["foo"] # Returns [0, 4]
# Throws ValueError if nothing is foundsome_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()]
list = ["foo", "bar", "baz"]
item_to_find = "foo"
if item_to_find in list:index = list.index(item_to_find)print("Index of the item is " + str(index))else:print("That word does not exist")
>>> expences = [2200, 2350, 2600, 2130, 2190]>>> 2000 in expencesFalse>>> 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>>>
>>> from operator import indexOf>>>>>>>>> help(indexOf)Help on built-in function indexOf in module _operator:
indexOf(a, b, /)Return the first index of b in a.
>>>>>>>>> indexOf(("foo", "bar", "baz"), "bar") # with tuple1>>> indexOf(["foo", "bar", "baz"], "bar") # with list1