传统Python语言的主要控制结构是for循环。然而,需要注意的是for循环在Pandas中不常用,因此Python中for循环的有效执行并不适用于Pandas模式。一些常见控制结构如下。
for循环
while循环
if/else语句
try/except语句
生成器表达式
列表推导式
模式匹配
所有的程序最终都需要一种控制执行流的方式。本节介绍一些控制执行流的技术。
01 for循环
for循环是Python的一种最基本的控制结构。使用for循环的一种常见模式是使用range函数生成数值范围,然后对其进行迭代。
res = range(3)
print(list(res))
#输出:[0, 1, 2]
for i in range(3):
print(i)
'''输出:
0
1
2
'''
for循环列表
使用for循环的另一种常见模式是对列表进行迭代。
martial_arts = ["Sambo","Muay Thai","BJJ"]
for martial_art in martial_arts:
print(f"{ martial_art} has influenced
modern mixed martial arts")
'''输出:
Sambo has influenced modern mixed martial arts
Muay Thai has influenced modern mixed martial arts
BJJ has influenced modern mixed martial arts
'''
02 while循环
while循环是一种条件有效就会重复执行的循环方式。while循环的常见用途是创建无限循环。在本示例中,while循环用于过滤函数,该函数返回两种攻击类型中的一种。
def attacks():
list_of_attacks = ["lower_body", "lower_body",
"upper_body"]
print("There are a total of {lenlist_of_attacks)}
attacks coming!")
for attack in list_of_ attacks:
yield attack
attack = attacks()
count = 0
while next(attack) == "lower_body":
count +=1
print(f"crossing legs to prevent attack #{count}")
else:
count += 1
print(f"This is not lower body attack,
I will cross my arms for# count}")
'''输出:
There are a total of 3 attacks coming!
crossing legs to prevent attack #1
crossing legs to prevent attack #2
This is not a lower body attack, I will cross my arms for #3
'''
03 if/else语句
if/else语句是一条在判断之间进行分支的常见语句。在本示例中,if/elif用于匹配分支。如果没有匹配项,则执行最后一条else语句。
def recommended_attack(position):
"""Recommends an attack based on the position"""
if position == "full_guard":
print(f"Try an armbar attack")
elif position == "half_guard":
print(f"Try a kimura attack")
elif position == "fu1l_mount":
print(f"Try an arm triangle")
else:
print(f"You're on your own,
there is no suggestion for an attack")
recommended_attack("full_guard")#输出:Try an armbar attack
recommended_attack("z_guard")
#输出:You're on your own, there is no suggestion for an attack
04 生成器表达式
生成器表达式建立在yield语句的概念上,它允许对序列进行惰性求值。生成器表达式的益处是,在实际求值计算前不会对任何内容进行求值或将其放入内存。这就是下面的示例可以在生成的无限随机攻击序列中执行的原因。