python判断列表中是否有某个数字

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

注意:

  1. 使用以上方法时,需要注意列表中的元素类型。如果列表中包含不同类型的元素,可能会导致结果不准确。
  2. 使用 index() 方法时,需要注意如果列表中存在多个相同的元素,index() 方法只会返回第一个出现位置的索引值。如果需要查找所有相同元素的索引位置,可以使用循环遍历列表的方式来实现。
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值