For a list ["foo", "bar", "baz"]
and an item in the list "bar"
, how do I get its index (1) in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
index()
returns the first index of value!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:All of the proposed functions here reproduce inherent language behavior but obscure what's going on.
Why write a function with exception handling if the language provides the methods to do what you want itself?
Since Python lists are zero-based, we can use the zip built-in function as follows:
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.)
Let’s give the name
lst
to the list that you have. One can convert the listlst
to anumpy 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.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:
If you may have duplicate elements, and need to return all of their indices: