for循环、in、not in

it2026-05-14  1

for循环、in、not in

for循环可以遍历集合中任意一个元素

1 a = ["hello", "world", "dlrb"] 2 for b in a: 3 print(b)

我们定义了一个集合a,通过for循环指定变量b遍历集合a,最后print变量b输出集合中的所有元素

输出结果:

hello world dlrb

或者使用for循环输出字符串中的每个元素:

1 a = "dlrb" 2 for b in a: 3 print(b)

输出结果:

d l r b

 

我们还可以通过几种方法查找某个元素是否在集合中:

1 a = ["hello", "world", "dlrb"] 2 b = "dlrb" 3 if b in a: 4 print("yes") 5 else: 6 print("no")

我们定义了一个集合a,定义了一个变量b,我们查找变量b所代表的字符串是否在集合a内,输出结果:

yes

not in的就是元素不在里面,用法都是一样的

1 a = ["hello", "world", "dlrb"] 2 b = "dlrb" in a 3 print(b)

我们定义了一个集合a,定义了一个变量b是一个判定语句:“dlrb”在集合a里面,根据结果会返回True或者False,输出结果:

True

 for循环中break、continue同样适用

1 a = "hello" 2 for i in a: 3 if i == "e": 4 continue 5 print(i)

输出结果:

h l l o

我们输出除e之外的所有字符

a = "hello" for i in a: if i == "e": break print(i)

输出结果:

h

我们输出每个字符但遇到e便停止循环

 

同样for循环中可以插入if、esle语句

1 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 2 for b in a: 3 if b%2 == 0: 4 print(b) 5 else: 6 pass

我们定义了一个集合a:里面是整数,我们想要输出集合a中的所有偶数,输出结果:

2 4 6 8 10 posted on 2019-04-09 10:29 恒笛 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/xwqhl/p/10675377.html

最新回复(0)