Python的控制结构之For、While、If循环问题
- for循环
- while循环
- if/else语句
- try/except语句
- 生成器表达式
- 列表推导式
- 模式匹配
所有的程序最终都需要一种控制执行流的方式。本节介绍一些控制执行流的技术。
01for循环
for循环是Python的一种最基本的控制结构。使用for循环的一种常见模式是使用range函数生成数值范围,然后对其进行迭代。
res=range(3) print(list(res)) #输出:[0,1,2] foriinrange(3): print(i) '''输出: 0 1 2 '''
for循环列表
使用for循环的另一种常见模式是对列表进行迭代。
martial_arts=["Sambo","MuayThai","BJJ"]
formartial_artinmartial_arts:
print(f"{martial_art}hasinfluenced\
modernmixedmartialarts")
'''输出:
Sambohasinfluencedmodernmixedmartialarts
MuayThaihasinfluencedmodernmixedmartialarts
BJJhasinfluencedmodernmixedmartialarts
'''
02while循环
while循环是一种条件有效就会重复执行的循环方式。while循环的常见用途是创建无限循环。在本示例中,while循环用于过滤函数,该函数返回两种攻击类型中的一种。
defattacks():
list_of_attacks=["lower_body","lower_body",
"upper_body"]
print("Thereareatotalof{lenlist_of_attacks)}\
attackscoming!")
forattackinlist_of_attacks:
yieldattack
attack=attacks()
count=0
whilenext(attack)=="lower_body":
count+=1
print(f"crossinglegstopreventattack#{count}")
else:
count+=1
print(f"Thisisnotlowerbodyattack,\
Iwillcrossmyarmsfor#count}")
'''输出:
Thereareatotalof3attackscoming!
crossinglegstopreventattack#1
crossinglegstopreventattack#2
Thisisnotalowerbodyattack,Iwillcrossmyarmsfor#3
'''
03if/else语句
if/else语句是一条在判断之间进行分支的常见语句。在本示例中,if/elif用于匹配分支。如果没有匹配项,则执行最后一条else语句。
defrecommended_attack(position):
"""Recommendsanattackbasedontheposition"""
ifposition=="full_guard":
print(f"Tryanarmbarattack")
elifposition=="half_guard":
print(f"Tryakimuraattack")
elifposition=="fu1l_mount":
print(f"Tryanarmtriangle")
else:
print(f"You'reonyourown,\
thereisnosuggestionforanattack")
recommended_attack("full_guard")#输出:Tryanarmbarattack
recommended_attack("z_guard")
#输出:You'reonyourown,thereisnosuggestionforanattack
04生成器表达式
生成器表达式建立在yield语句的概念上,它允许对序列进行惰性求值。生成器表达式的益处是,在实际求值计算前不会对任何内容进行求值或将其放入内存。这就是下面的示例可以在生成的无限随机攻击序列中执行的原因。
在生成器管道中,诸如“arm_triangle”的小写攻击被转换为“ARM_TRIANGLE”,接下来删除其中的下划线,得到“ARMTRIANGLE”。
deflazy_return_random_attacks():
"""Yieldattackseachtime"""
importrandom
attacks={"kimura":"upper_body",
"straight_ankle_lock":"lower_body",
"arm_triangle":"upper_body",
"keylock":"upper_body",
"knee_bar":"lower_body"}
whileTrue:
random_attackrandom.choices(list(attacks.keys()))
yieldrandomattack
#MakeallattacksappearasUpperCase
upper_case_attacks=\
(attack.pop().upper()forattackin\
lazy_return_random_attacks())
next(upper-case_attacks)
#输出:ARM-TRIANGLE
##GeneratorPipeline:Oneexpressionchainsintothenext
#MakeallattacksappearasUpperCase
upper-case_attacks=\
(attack.pop().upper()forattackin\
lazy_return_random_attacks())
#removetheunderscore
removeunderscore=\
(attack.split("_")forattackin\
upper-case_attacks)
#createanewphrase
new_attack_phrase=\
("".join(phrase)forphrasein\
remove_underscore)
next(new_attack_phrase)
#输出:'STRAIGHTANKLELOCK'
fornumberinrange(10):
print(next(new_attack_phrase))
'''输出:
KIMURA
KEYLOCK
STRAIGHTANKLELOCK
'''
05列表推导式
语法上列表推导式与生成器表达式类似,然而直接对比它们,会发现列表推导式是在内存中求值。此外,列表推导式是优化的C代码,可以认为这是对传统for循环的重大改进。
martial_arts=["Sambo","MuayThai","BJJ"] new_phrases[f"mixedMartialArtsisinfluencedby\ (martial_art)"formartial_artinmartial_arts] print(new_phrases) ['MixedMartialArtsisinfluencedbySambo',\ 'MixedMartialArtsisinfluencedbyMuayThai',\ 'MixedMartialArtsisinfluencedbyBJJ']
06中级主题
有了这些基础知识后,重要的是不仅要了解如何创建代码,还要了解如何创建可维护的代码。创建可维护代码的一种方法是创建一个库,另一种方法是使用已经安装的第三方库编写的代码。其总体思想是最小化和分解复杂性。
使用Python编写库
使用Python编写库非常重要,之后将该库导入项目无须很长时间。下面这些示例是编写库的基础知识:在存储库中有一个名为funclib的文件夹,其中有一个_init_.py文件。要创建库,在该目录中需要有一个包含函数的模块。
首先创建一个文件。
touchfunclib/funcmod.py
然后在该文件中创建一个函数。
"""Thisisasimplemodule"""
deflist_of_belts_in_bjj():
"""ReturnsalistofthebeltsinBrazilianjiu-jitsu"""
belts=["white","blue","purple","brown","black"]
returnbelts
importsys;sys.path.append("..")
fromfunclibimportfuncmod
funcmod.list_of_belts_in-bjj()
#输出:['white','blue','purple','brown','black']
导入库
如果库是上面的目录,则可以用Jupyter添加sys.path.append方法来将库导入。接下来,使用前面创建的文件夹/文件名/函数名的命名空间导入模块。
安装第三方库
可使用pipinstall命令安装第三方库。请注意,conda命令(
https://conda.io/docs/user-guide/tasks/manage-pkgs.html)是pip命令的可选替代命令。如果使用conda命令,那么pip命令也会工作得很好,因为pip是virtualenv虚拟环境的替代品,但它也能直接安装软件包。
安装pandas包。
pipinstallpandas
另外,还可使用requirements.txt文件安装包。
>carequirements.txt pylint pytest pytest-cov click jupyter nbval >pipinstall-rrequirements.txt
下面是在JupyterNotebook中使用小型库的示例。值得指出的是,在JupyterNotebook中创建程序代码组成的巨型蜘蛛网很容易,而且非常简单的解决方法就是创建一些库,然后测试并导入这些库。
"""Thisisasimplemodule""" importpandasaspd deflist_of_belts_in_bjj(): """ReturnsalistofthebeltsinBrazilianjiu-jitsu""" belts=["white","blue","purple","brown","black"] returnbelts defcount_belts(): """UsesPandastocountnumberofbelts""" belts=list_of_belts_in_bjj() df=pd.Dataframe(belts) res=df.count() count=res.values.tolist()[0] returncount fromfunclib.funcmodimportcount_belts print(count_belts()) #输出:5
类
可在JupyterNotebook中重复使用类并与类进行交互。最简单的类类型就是一个名称,类的定义形式如下。
classCompetitor:pass
该类可实例化为多个对象。
classCompetitor:pass
conor=Competitor()
conor.name="ConorMcGregor"
conor.age=29
conor.weight=155
nate=Competitor()
nate.name="NateDiaz"
nate.age=30
nate.weight=170
defprint_competitor_age(object):
"""Printoutagestatisticsaboutacompetitor"""
print(f"{object.name}is{object.age}yearsold")
print_competitor_age(nate)
#输出:NateDiazis30yearsold
print_competitor_age(conor)
#输出:ConorMcGregoris29yearsold
类和函数的区别
类和函数的主要区别包括:
- 函数更容易解释。
- 函数(典型情况下)只在函数内部具有状态,而类在函数外部保持不变的状态。
- 类能以复杂性为代价提供更高级别的抽象。
总结
到此这篇关于Python的控制结构:For、While、If…的文章就介绍到这了,更多相关Python控制结构If、While、For内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!