
作者:挪亚·吉夫特(Noah Gift)
来源:大数据DT(ID:hzdashuju)
内容摘编自《人工智能开发实践:云端机器学习导论》
导读:本文介绍Python中的常见控制结构。
传统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语句的概念上,它允许对序列进行惰性求值。生成器表达式的益处是,在实际求值计算前不会对任何内容进行求值或将其放入内存。这就是下面的示例可以在生成的无限随机攻击序列中执行的原因。
在生成器管道中,诸如 “arm_triangle”的小写攻击被转换为“ARM_TRIANGLE”,接下来删除其中的下划线,得到“ARM TRIANGLE”。
def lazy_return_random_attacks():
"""Yield attacks each time"""
import random
attacks = {"kimura": "upper_body",
"straight_ankle_lock": "lower_body",
"arm_triangle": "upper_body",
"keylock": "upper_body",
"knee_bar": "lower_body"}
while True:
random_attack random.choices(list(attacks.keys()))
yield random attack
#Make all attacks appear as Upper Case
upper_case_attacks = \
(attack.pop().upper() for attack in \
lazy_return_random_attacks())
next(upper-case_attacks)
#输出:ARM-TRIANGLE
## Generator Pipeline: One expression chains into the next
#Make all attacks appear as Upper Case
upper-case_attacks =\
(attack. pop().upper() for attack in\
lazy_return_random_attacks())
#remove the underscore
remove underscore =\
(attack.split("_")for attack in\
upper-case_attacks)
#create a new phrase
new_attack_phrase =\
(" ".join(phrase) for phrase in\
remove_underscore)
next(new_attack_phrase)
#输出:'STRAIGHT ANKLE LOCK'
for number in range(10):
print(next(new_attack_phrase))
'''输出:
KIMURA
KEYLOCK
STRAIGHT ANKLE LOCK
'''
05 列表推导式
语法上列表推导式与生成器表达式类似,然而直接对比它们,会发现列表推导式是在内存中求值。此外,列表推导式是优化的C代码,可以认为这是对传统for循环的重大改进。
martial_arts = ["Sambo", "Muay Thai", "BJJ"]
new_phrases [f"mixed Martial Arts is influenced by \
(martial_art)" for martial_art in martial_arts]
print(new_phrases)
['Mixed Martial Arts is influenced by Sambo', \
'Mixed Martial Arts is influenced by Muay Thai', \
'Mixed Martial Arts is influenced by BJJ']
06 中级主题
有了这些基础知识后,重要的是不仅要了解如何创建代码,还要了解如何创建可维护的代码。创建可维护代码的一种方法是创建一个库,另一种方法是使用已经安装的第三方库编写的代码。其总体思想是最小化和分解复杂性。
使用Python编写库
使用Python编写库非常重要,之后将该库导入项目无须很长时间。下面这些示例是编写库的基础知识:在存储库中有一个名为funclib的文件夹,其中有一个_init_ .py文件。要创建库,在该目录中需要有一个包含函数的模块。
首先创建一个文件。
touch funclib/funcmod.py
然后在该文件中创建一个函数。
"""This is a simple module"""
def list_of_belts_in_bjj():
"""Returns a list of the belts in Brazilian jiu-jitsu"""
belts= ["white", "blue", "purple", "brown", "black"]
return belts
import sys;sys.path.append("..")
from funclib import funcmod
funcmod.list_of_belts_in-bjj()
#输出:['white', 'blue', 'purple', 'brown', 'black']
导入库
如果库是上面的目录,则可以用Jupyter添加sys.path.append方法来将库导入。接下来,使用前面创建的文件夹/文件名/函数名的命名空间导入模块。
安装第三方库
可使用pip install命令安装第三方库。请注意,conda命令(https://conda.io/docs/user-guide/tasks/manage-pkgs.html)是pip命令的可选替代命令。如果使用conda命令,那么pip命令也会工作得很好,因为pip是virtualenv虚拟环境的替代品,但它也能直接安装软件包。
安装pandas包。
pip install pandas
另外,还可使用requirements.txt文件安装包。
> ca requirements.txt
pylint
pytest
pytest-cov
click
jupyter
nbval
> pip install -r requirements.txt
下面是在Jupyter Notebook中使用小型库的示例。值得指出的是,在Jupyter Notebook中创建程序代码组成的巨型蜘蛛网很容易,而且非常简单的解决方法就是创建一些库,然后测试并导入这些库。
"""This is a simple module"""
import pandas as pd
def list_of_belts_in_bjj():
"""Returns a list of the belts in Brazilian jiu-jitsu"""
belts = ["white", "blue", "purple", "brown", "black"]
return belts
def count_belts():
"""Uses Pandas to count number of belts"""
belts = list_of_belts_in_bjj()
df = pd.Dataframe(belts)
res = df.count()
count = res.values.tolist()[0]
return count
from funclib.funcmod import count_belts
print(count_belts())
#输出:5
类
可在Jupyter Notebook中重复使用类并与类进行交互。最简单的类类型就是一个名称,类的定义形式如下。
class Competitor: pass
该类可实例化为多个对象。
class Competitor: pass
conor = Competitor()
conor.name = "Conor McGregor"
conor.age = 29
conor.weight = 155
nate = Competitor()
nate.name = "Nate Diaz"
nate.age = 30
nate.weight = 170
def print_competitor _age(object):
"""Print out age statistics about a competitor"""
print(f"{object.name} is {object.age} years old")
print_competitor_age(nate)
#输出:Nate Diaz is 30 years old
print_competitor_age(conor)
#输出:Conor McGregor is 29 years old
类和函数的区别
类和函数的主要区别包括:
函数更容易解释。
函数(典型情况下)只在函数内部具有状态,而类在函数外部保持不变的状态。
类能以复杂性为代价提供更高级别的抽象。
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
2025 年,数据如同数字时代的 DNA,编码着人类社会的未来图景,驱动着商业时代的运转。从全球互联网用户每天产生的2.5亿TB数据, ...
2025-06-052025 年,数据如同数字时代的 DNA,编码着人类社会的未来图景,驱动着商业时代的运转。从全球互联网用户每天产生的2.5亿TB数据, ...
2025-05-27CDA数据分析师证书考试体系(更新于2025年05月22日)
2025-05-26解码数据基因:从数字敏感度到逻辑思维 每当看到超市货架上商品的排列变化,你是否会联想到背后的销售数据波动?三年前在零售行 ...
2025-05-23在本文中,我们将探讨 AI 为何能够加速数据分析、如何在每个步骤中实现数据分析自动化以及使用哪些工具。 数据分析中的AI是什么 ...
2025-05-20当数据遇见人生:我的第一个分析项目 记得三年前接手第一个数据分析项目时,我面对Excel里密密麻麻的销售数据手足无措。那些跳动 ...
2025-05-20在数字化运营的时代,企业每天都在产生海量数据:用户点击行为、商品销售记录、广告投放反馈…… 这些数据就像散落的拼图,而相 ...
2025-05-19在当今数字化营销时代,小红书作为国内领先的社交电商平台,其销售数据蕴含着巨大的商业价值。通过对小红书销售数据的深入分析, ...
2025-05-16Excel作为最常用的数据分析工具,有没有什么工具可以帮助我们快速地使用excel表格,只要轻松几步甚至输入几项指令就能搞定呢? ...
2025-05-15数据,如同无形的燃料,驱动着现代社会的运转。从全球互联网用户每天产生的2.5亿TB数据,到制造业的传感器、金融交易 ...
2025-05-15大数据是什么_数据分析师培训 其实,现在的大数据指的并不仅仅是海量数据,更准确而言是对大数据分析的方法。传统的数 ...
2025-05-14CDA持证人简介: 万木,CDA L1持证人,某电商中厂BI工程师 ,5年数据经验1年BI内训师,高级数据分析师,拥有丰富的行业经验。 ...
2025-05-13CDA持证人简介: 王明月 ,CDA 数据分析师二级持证人,2年数据产品工作经验,管理学博士在读。 学习入口:https://edu.cda.cn/g ...
2025-05-12CDA持证人简介: 杨贞玺 ,CDA一级持证人,郑州大学情报学硕士研究生,某上市公司数据分析师。 学习入口:https://edu.cda.cn/g ...
2025-05-09CDA持证人简介 程靖 CDA会员大咖,畅销书《小白学产品》作者,13年顶级互联网公司产品经理相关经验,曾在百度、美团、阿里等 ...
2025-05-07相信很多做数据分析的小伙伴,都接到过一些高阶的数据分析需求,实现的过程需要用到一些数据获取,数据清洗转换,建模方法等,这 ...
2025-05-06以下的文章内容来源于刘静老师的专栏,如果您想阅读专栏《10大业务分析模型突破业务瓶颈》,点击下方链接 https://edu.cda.cn/g ...
2025-04-30CDA持证人简介: 邱立峰 CDA 数据分析师二级持证人,数字化转型专家,数据治理专家,高级数据分析师,拥有丰富的行业经验。 ...
2025-04-29CDA持证人简介: 程靖 CDA会员大咖,畅销书《小白学产品》作者,13年顶级互联网公司产品经理相关经验,曾在百度,美团,阿里等 ...
2025-04-28CDA持证人简介: 居瑜 ,CDA一级持证人国企财务经理,13年财务管理运营经验,在数据分析就业和实践经验方面有着丰富的积累和经 ...
2025-04-27