1. Just use in
and not in
keywords
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:
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:
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:
Note:
- The requirement of converting to numpy array is that your elements are numbers, not strings.
- 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.