
作者:挪亞·吉夫特(Noah Gift)
來源:大數(shù)據(jù)DT(ID:hzdashuju)
內(nèi)容摘編自《人工智能開發(fā)實(shí)踐:云端機(jī)器學(xué)習(xí)導(dǎo)論》
導(dǎo)讀:本文介紹Python中的常見控制結(jié)構(gòu)。
傳統(tǒng)Python語言的主要控制結(jié)構(gòu)是for循環(huán)。然而,需要注意的是for循環(huán)在Pandas中不常用,因此Python中for循環(huán)的有效執(zhí)行并不適用于Pandas模式。一些常見控制結(jié)構(gòu)如下。
for循環(huán)
while循環(huán)
if/else語句
try/except語句
生成器表達(dá)式
列表推導(dǎo)式
模式匹配
所有的程序最終都需要一種控制執(zhí)行流的方式。本節(jié)介紹一些控制執(zhí)行流的技術(shù)。
01 for循環(huán)
for循環(huán)是Python的一種最基本的控制結(jié)構(gòu)。使用for循環(huán)的一種常見模式是使用range函數(shù)生成數(shù)值范圍,然后對(duì)其進(jìn)行迭代。
res = range(3)
print(list(res))
#輸出:[0. 1. 2]
for i in range(3):
print(i)
'''輸出:
0
1
2
'''
for循環(huán)列表
使用for循環(huán)的另一種常見模式是對(duì)列表進(jìn)行迭代。
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循環(huán)
while循環(huán)是一種條件有效就會(huì)重復(fù)執(zhí)行的循環(huán)方式。while循環(huán)的常見用途是創(chuàng)建無限循環(huán)。在本示例中,while循環(huán)用于過濾函數(shù),該函數(shù)返回兩種攻擊類型中的一種。
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語句是一條在判斷之間進(jìn)行分支的常見語句。在本示例中,if/elif用于匹配分支。如果沒有匹配項(xiàng),則執(zhí)行最后一條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 生成器表達(dá)式
生成器表達(dá)式建立在yield語句的概念上,它允許對(duì)序列進(jìn)行惰性求值。生成器表達(dá)式的益處是,在實(shí)際求值計(jì)算前不會(huì)對(duì)任何內(nèi)容進(jìn)行求值或?qū)⑵浞湃雰?nèi)存。這就是下面的示例可以在生成的無限隨機(jī)攻擊序列中執(zhí)行的原因。
在生成器管道中,諸如 “arm_triangle”的小寫攻擊被轉(zhuǎn)換為“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 列表推導(dǎo)式
語法上列表推導(dǎo)式與生成器表達(dá)式類似,然而直接對(duì)比它們,會(huì)發(fā)現(xiàn)列表推導(dǎo)式是在內(nèi)存中求值。此外,列表推導(dǎo)式是優(yōu)化的C代碼,可以認(rèn)為這是對(duì)傳統(tǒng)for循環(huán)的重大改進(jìn)。
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 中級(jí)主題
有了這些基礎(chǔ)知識(shí)后,重要的是不僅要了解如何創(chuàng)建代碼,還要了解如何創(chuàng)建可維護(hù)的代碼。創(chuàng)建可維護(hù)代碼的一種方法是創(chuàng)建一個(gè)庫,另一種方法是使用已經(jīng)安裝的第三方庫編寫的代碼。其總體思想是最小化和分解復(fù)雜性。
使用Python編寫庫
使用Python編寫庫非常重要,之后將該庫導(dǎo)入項(xiàng)目無須很長時(shí)間。下面這些示例是編寫庫的基礎(chǔ)知識(shí):在存儲(chǔ)庫中有一個(gè)名為funclib的文件夾,其中有一個(gè)_init_ .py文件。要?jiǎng)?chuàng)建庫,在該目錄中需要有一個(gè)包含函數(shù)的模塊。
首先創(chuàng)建一個(gè)文件。
touch funclib/funcmod.py
然后在該文件中創(chuàng)建一個(gè)函數(shù)。
"""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']
導(dǎo)入庫
如果庫是上面的目錄,則可以用Jupyter添加sys.path.append方法來將庫導(dǎo)入。接下來,使用前面創(chuàng)建的文件夾/文件名/函數(shù)名的命名空間導(dǎo)入模塊。
安裝第三方庫
可使用pip install命令安裝第三方庫。請(qǐng)注意,conda命令(https://conda.io/docs/user-guide/tasks/manage-pkgs.html)是pip命令的可選替代命令。如果使用conda命令,那么pip命令也會(huì)工作得很好,因?yàn)閜ip是virtualenv虛擬環(huán)境的替代品,但它也能直接安裝軟件包。
安裝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中創(chuàng)建程序代碼組成的巨型蜘蛛網(wǎng)很容易,而且非常簡(jiǎn)單的解決方法就是創(chuàng)建一些庫,然后測(cè)試并導(dǎo)入這些庫。
"""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中重復(fù)使用類并與類進(jìn)行交互。最簡(jiǎn)單的類類型就是一個(gè)名稱,類的定義形式如下。
class Competitor: pass
該類可實(shí)例化為多個(gè)對(duì)象。
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
類和函數(shù)的區(qū)別
類和函數(shù)的主要區(qū)別包括:
函數(shù)更容易解釋。
函數(shù)(典型情況下)只在函數(shù)內(nèi)部具有狀態(tài),而類在函數(shù)外部保持不變的狀態(tài)。
類能以復(fù)雜性為代價(jià)提供更高級(jí)別的抽象。
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03