[Python3 填坑] 008 索引君的朋友 in


  • 挖坑时间:2019/01/10
  • 明细
坑的编码内容
Py006-2索引君的朋友 in



2. 开始填坑

(1) 前情提要

  • 上回说到,index() 的索引值超出范围会抛出异常,如
list0 = [0, 1, 2, 3, 4, 5, 6]
print(list0.index(8))
  • 运行结果

ValueError: 8 is not in list

(2) 索引君的朋友 in 上线

  • 少废话,上例子
# 例1.1

list1 = [0, 1, 2, 3, 4, 5, 6]
if 8 in list1:
    print("8 is in this list.")
else:
    print("Sorry, 8 is not in this list.")
  • 运行结果

Sorry, 8 is not in this list.


# 例1.2

list1 = [0, 1, 2, 3, 4, 5, 6]
boolean = 8 in list1
print(boolean)
  • 运行结果

False

in 返回 True 或 False,且不报错,但不能像 index() 那样索引到具体的值。


(3) 既然说了 in,不妨再说一说 not in

  • 少废话,上例子
# 例2

list2 = [0, 1, 2, 3, 4, 5, 6]
if 8 not in list1:
    print("8 is in this list.")
else:
    print("Sorry, 8 is not in this list.")
boolean = 8 in list2
print(boolean)
  • 运行结果

8 is in this list.
False


(4) 一些补充

  • in、not in 只能判断一层关系
# 例3

list3 = [0, 1, 2, [3, 4, 5]]
if 3 in list3:
    print("YES")
else:
    print("NO")
  • 运行结果

NO


  • 解决办法
# 例4

list4 = [0, 1, 2, [3, 4, 5]]
if 3 in list4[3]:
    print("YES")
else:
    print("NO")
  • 运行结果

YES


我的学识有限,如果有同学、老师或者前辈看到我写的东西,发现错误之处,还请不吝赐教!谢谢!

转载于:https://www.cnblogs.com/yorkyu/p/10316064.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值