1.使用count()方法
#根据出现次数判断是否存在某个数字
my_list = [1, 2, 4, 4, 4, 5]
for num in range(4,7):
if my_list.count(num) > 0:
print("{} is in the list".format(num))
else:
print("{} is not in the list".format(num))
#4 is in the list
# 5 is in the list
# 6 is not in the list
2.使用in方法:
my_list = [1, 2, 4, 4, 4, 5]
for num in range(4,7):
if num in my_list:
print("{} is in the list".format(num))
else:
print("{} is not in the list".format(num))
# 4 is in the list
# 5 is in the list
# 6 is not in the list
3.使用index()方法:
my_list = [1, 2, 4, 4, 4, 5]
try:
index = my_list.index(3)
print("3 is in the list, index is", index)
except ValueError:
print("3 is not in the list")
#3 is not in the list
注意:
- 使用以上方法时,需要注意列表中的元素类型。如果列表中包含不同类型的元素,可能会导致结果不准确。
- 使用 index() 方法时,需要注意如果列表中存在多个相同的元素,index() 方法只会返回第一个出现位置的索引值。如果需要查找所有相同元素的索引位置,可以使用循环遍历列表的方式来实现。