目录
1. print( 坑的信息 )
- 挖坑时间: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
我的学识有限,如果有同学、老师或者前辈看到我写的东西,发现错误之处,还请不吝赐教!谢谢!