Finding the index of an item given a list containi

2018-12-31 01:56发布

For a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index (1) in Python?

标签: python list
28条回答
无色无味的生活
2楼-- · 2018-12-31 02:09

index() returns the first index of value!

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

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"])
查看更多
骚的不知所云
3楼-- · 2018-12-31 02:09

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

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

    try:
        index = array.index('search_keyword')
    except ValueError:
        index = -1
查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 02:10

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?

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 02:10

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

>>> [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.)

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 02:10

Let’s give the name lst to the list that you have. One can convert the list lst to a numpy array. And, then use numpy.where to get the index of the chosen item in the list. Following is the way in which you will implement it.

import numpy as np

lst = ["foo", "bar", "baz"]  #lst: : 'list' data type
print np.where( np.array(lst) == 'bar')[0][0]

>>> 1
查看更多
倾城一夜雪
7楼-- · 2018-12-31 02:14

If performance is of concern:

It is mentioned in numerous answers that the built-in method of list.index(item) method is an O(n) algorithm. It is fine if you need to perform this once. But if you need to access the indices of elements a number of times, it makes more sense to first create a dictionary (O(n)) of item-index pairs, and then access the index at O(1) every time you need it.

If you are sure that the items in your list are never repeated, you can easily:

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.

If you may have duplicate elements, and need to return all of their indices:

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]
查看更多
登录 后发表回答