During the development process, we often encounter information about specific elements in the data, such as the station nearest to the destination, the most expensive items in the window, etc. what to do? Look at the following
Method 1: Use the array's own characteristics (target), where a is your target list, and target is the value corresponding to the subscript you need
li = [10,8,9,26,72,6,28] print((8))
But what if there are multiple 8s in a?
We found that this method can only obtain the subscript of the first matching value (you can try o_o)
So, let's take a look at our second solution:
Method 2: Use the enumerate function.
>>> li = [10,8,9,26,72,6,28] >>> print (enumerate(li)) <enumerate object at 0x0000000002B9A990>
It turns out that the output type of enumerate is the enumerate object object, so we can follow
>>> li [10, 8, 9, 26, 72, 6, 28] >>> print(list(enumerate(li))) [(0, 10), (1, 8), (2, 9), (3, 26), (4, 72), (5, 6), (6, 28)] >>> print([i for i,j in enumerate(li) if j == 8]) [1]
Look again, what if there are multiple ‘8’ in a?
>>> (8) >>> (8) >>> li [10, 8, 9, 26, 72, 6, 28, 8, 8] >>> print((8)) 1 #No one answers the questions encountered during study? The editor has created a Python learning exchange group: 531509025>>> print(list(enumerate(li))) [(0, 10), (1, 8), (2, 9), (3, 26), (4, 72), (5, 6), (6, 28), (7, 8), (8, 8)] >>> print([i for i,j in enumerate(li) if j == 8]) [1, 7, 8]
It can be seen that the index() method of list is to find the first matching value in list.
Enumerate tuples elements in list (of course, also include other types), and then we use the loop method to obtain the corresponding matching results. Therefore, the second solution can be used to get the repeated values without missing a single omission.
This is the article about two methods of obtaining the index of specified elements in lists in Python. For more related contents of obtaining the index of specified elements in lists in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!