京公网安备 11010802034615号
经营许可证编号:京B2-20210330
作者:挪亚·吉夫特(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
大部分人用 AI 写东西,是"一次一份"。但办公室里真正耗时间的,往往是"同一份东西做 N 遍"。 这篇讲的就是这类活:一家做企业内 ...
2026-11-30对账这件事,最能看出一个人会不会用 AI。 因为它不是"生成内容",是"把两份不一样的东西对上"。这类活没有标准答案,只有一堆例 ...
2026-11-30让优质知识跨越语言,被更多人看见 世界各地不缺好课,缺的是能读懂它的语言。原版英文,术语密集,字幕能救句子,救不了概念— ...
2026-11-30 面对一堆数据,新手最常见的状态是:指标都在眼前,却不知道从哪下手。其实数据分析没有那么多玄学,绝大多数业务问题,都可 ...
2026-11-27一句话答案:把文件路径和问题一起给它,它自己读表、清洗、算数、出图,最后给你一个能直接发出去的文件。你负责提问题和验收, ...
2026-11-27这三个名字经常被放在一起问,但它们根本不在同一层。搞混了,选型一定出错。 点击链接领取WorkBuddy体验课:https://edu.cda.cn ...
2026-11-27 在做有序分组的趋势分析时,经常被问到一个问题:线性趋势检验(linear trend test)的自由度是 1 吗?答案是:在单因素方差 ...
2026-11-26很多人把这两个放在一起比,其实它们解决的不是同一层问题。 点击链接领取WorkBuddy体验课:https://edu.cda.cn/goods/show/4341 ...
2026-11-26直接回答:有免费额度,但免费额度不够日常重度使用。值不值得付费,取决于你每个月的"文档活儿"有多少。 点击链接领取WorkBuddy ...
2026-11-26 在质量分析和数据报表里,趋势图和柏拉图(帕累托图)都是常用图形,也都可能是"柱子加折线"的组合,很容易被混用。但它们回 ...
2026-11-25这篇只讲一件事:让你在 20 分钟内真正跑通一个任务,而不是装完就放着。 点击链接领取WorkBuddy体验课:https://edu.cda.cn/goo ...
2026-11-25一句话答案:WorkBuddy 是腾讯做的桌面 AI 办公助手。你用一句话说清想要什么结果,它自己拆步骤、写文件、做表格、做 PPT,最后 ...
2026-11-25 营销里最常见的两种状态:一种是凭经验拍板,"我觉得这个渠道有效";另一种是报表堆了一堆,流量、曝光、点赞都在涨,却不知 ...
2026-11-24 "你还没点购买,货已经在你家几公里外的快递车上了。"这句话听起来像科幻,但它正是亚马逊在 2013 年拿到的一项专利里写的构 ...
2026-11-24月度经营会上,一张饼图被切成十一块。 颜色相近的两块挨在一起,投影仪上几乎分不出来。老板看了三秒,问了一句:到底谁在涨? ...
2026-11-24 很多人把预处理理解成"建模前随手洗一下数据":丢进工具,填个空、删个重复,就开始跑分析。但真正做过数据项目的人都知道, ...
2026-11-23 SQL 不是数据库工程师的专利,而是数据分析、运营、产品做业务取数和统计的基本功。绝大多数经营报表、用户分析、漏斗留存、 ...
2026-11-23这周你大概又经历过一次:报表自己跑了,SQL 让 AI 写了,连周报初稿都不用自己动手。你一边松口气,一边心里发慌——那我还剩什 ...
2026-11-23CDA数据分析师 出品 作者:李诗怡 多表进阶与 DDL/DML 连接 · 子查询 · 合并 · 建表与书写规范 ” 三、DQL 多表进阶:连 ...
2026-11-20 前面讲了怎么搭指标体系,但很多团队卡在最后一步:高层定了一个漂亮的目标,往下一层层写进周报,最后却落不到任何人的具体 ...
2026-11-20