Python determines whether an element is in the list and returns the index of the element in the list

1. Just use inand not inkeywords

number=[1,2,3,4,5]
if 1 in number:
    print("1 in number")
if 0 not in number:
    print("0 not in number")

Result:
Insert picture description here
2. If an element is in the list, it can be used index()to get the index subscript.

number=[1,2,3,4,5,3]
number.index(3)

Result:
Insert picture description here
But we found that there are obviously two 3s, but only the first index is returned. We can return all through numpy.

import numpy
number=[1,2,3,4,5,3]
num=np.array(number)
np.argwhere(num==3)

Result:
Insert picture description here
Note:

  1. The requirement of converting to numpy array is that your elements are numbers, not strings.
  2. When finding the index of an element, the index() method of the list can only be used when the element is in the list, otherwise python will report an error!

For 2, that is to say, if you want to check the index of x in the list a, it is recommended to use it like this:

a=[1,2,3,4,5]
x=3
index=-1
if x in a:
    index=a.index(x)
print(index)

In this case, if the element is in it, the first index is obtained, which is greater than or equal to 0, otherwise index=-1.

Guess you like

Origin blog.csdn.net/qq_43391414/article/details/112323971