日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
一文看懂Python的控制結(jié)構(gòu):For、While、If…都有了

傳統(tǒng)Python語言的主要控制結(jié)構(gòu)是for循環(huán)。然而,需要注意的是for循環(huán)在Pandas中不常用,因此Python中for循環(huán)的有效執(zhí)行并不適用于Pandas模式。一些常見控制結(jié)構(gòu)如下。

成都創(chuàng)新互聯(lián)是專業(yè)的三臺網(wǎng)站建設(shè)公司,三臺接單;提供網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行三臺網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊,希望更多企業(yè)前來合作!

  • 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ù)值范圍,然后對其進(jìn)行迭代。

 
 
  1. res = range(3)
  2. print(list(res))
  3. #輸出:[0, 1, 2]
 
 
  1. for i in range(3):
  2. print(i)
  3. '''輸出:
  4. 0
  5. 1
  6. 2
  7. '''
  • for循環(huán)列表

使用for循環(huán)的另一種常見模式是對列表進(jìn)行迭代。

 
 
  1. martial_arts = ["Sambo","Muay Thai","BJJ"]
  2. for martial_art in martial_arts:
  3.     print(f"{ martial_art} has influenced\
  4.           modern mixed martial arts")
  5. '''輸出:
  6. Sambo has influenced modern mixed martial arts
  7. Muay Thai has influenced modern mixed martial arts
  8. BJJ has influenced modern mixed martial arts
  9. '''

02 while循環(huán)

while循環(huán)是一種條件有效就會重復(fù)執(zhí)行的循環(huán)方式。while循環(huán)的常見用途是創(chuàng)建無限循環(huán)。在本示例中,while循環(huán)用于過濾函數(shù),該函數(shù)返回兩種攻擊類型中的一種。

 
 
  1. def attacks():
  2.     list_of_attacks = ["lower_body", "lower_body",
  3.          "upper_body"]
  4.     print("There are a total of {lenlist_of_attacks)}\
  5.           attacks coming!")
  6.     for attack in list_of_ attacks:
  7.         yield attack
  8. attack = attacks()
  9. count = 0
  10. while next(attack) == "lower_body":
  11.     count +=1
  12.     print(f"crossing legs to prevent attack #{count}")
  13. else:
  14.     count += 1
  15.     print(f"This is not lower body attack, \
  16. I will cross my arms for# count}")
  17. '''輸出:
  18. There are a total of 3 attacks coming!
  19. crossing legs to prevent attack #1
  20. crossing legs to prevent attack #2
  21. This is not a lower body attack, I will cross my arms for #3
  22. '''

03 if/else語句

if/else語句是一條在判斷之間進(jìn)行分支的常見語句。在本示例中,if/elif用于匹配分支。如果沒有匹配項(xiàng),則執(zhí)行最后一條else語句。

 
 
  1. def recommended_attack(position):
  2.     """Recommends an attack based on the position"""
  3.     if position == "full_guard":
  4.         print(f"Try an armbar attack")
  5.     elif position == "half_guard":
  6.         print(f"Try a kimura attack")
  7.     elif position == "fu1l_mount":
  8.         print(f"Try an arm triangle")
  9.     else:
  10.         print(f"You're on your own, \
  11.          there is no suggestion for an attack")
 
 
  1. recommended_attack("full_guard")#輸出:Try an armbar attack
 
 
  1. recommended_attack("z_guard")
  2. #輸出:You're on your own, there is no suggestion for an attack

04 生成器表達(dá)式

生成器表達(dá)式建立在yield語句的概念上,它允許對序列進(jìn)行惰性求值。生成器表達(dá)式的益處是,在實(shí)際求值計算前不會對任何內(nèi)容進(jìn)行求值或?qū)⑵浞湃雰?nèi)存。這就是下面的示例可以在生成的無限隨機(jī)攻擊序列中執(zhí)行的原因。

在生成器管道中,諸如 “arm_triangle”的小寫攻擊被轉(zhuǎn)換為“ARM_TRIANGLE”,接下來刪除其中的下劃線,得到“ARM TRIANGLE”。

 
 
  1.  def lazy_return_random_attacks():
  2.      """Yield attacks each time"""
  3.      import random
  4.      attacks = {"kimura": "upper_body",
  5.             "straight_ankle_lock": "lower_body",
  6.             "arm_triangle": "upper_body",
  7.              "keylock": "upper_body",
  8.              "knee_bar": "lower_body"}
  9.      while True:
  10.          random_attack random.choices(list(attacks.keys()))
  11.          yield random attack
  12. #Make all attacks appear as Upper Case
  13. upper_case_attacks = \
  14.          (attack.pop().upper() for attack in \
  15.          lazy_return_random_attacks())
 
 
  1. next(upper-case_attacks)
  2. #輸出:ARM-TRIANGLE
 
 
  1. ## Generator Pipeline: One expression chains into the next
  2. #Make all attacks appear as Upper Case
  3. upper-case_attacks =\
  4.     (attack. pop().upper() for attack in\
  5.     lazy_return_random_attacks())
  6. #remove the underscore
  7. remove underscore =\
  8.     (attack.split("_")for attack in\
  9.     upper-case_attacks)
  10. #create a new phrase
  11. new_attack_phrase =\
  12.     (" ".join(phrase) for phrase in\
  13.     remove_underscore)
 
 
  1. next(new_attack_phrase)
  2. #輸出:'STRAIGHT ANKLE LOCK'
 
 
  1. for number in range(10):
  2.     print(next(new_attack_phrase))
  3. '''輸出:
  4. KIMURA
  5. KEYLOCK
  6. STRAIGHT ANKLE LOCK
  7. '''

05 列表推導(dǎo)式

語法上列表推導(dǎo)式與生成器表達(dá)式類似,然而直接對比它們,會發(fā)現(xiàn)列表推導(dǎo)式是在內(nèi)存中求值。此外,列表推導(dǎo)式是優(yōu)化的C代碼,可以認(rèn)為這是對傳統(tǒng)for循環(huán)的重大改進(jìn)。

 
 
  1. martial_arts = ["Sambo", "Muay Thai", "BJJ"]
  2. new_phrases [f"mixed Martial Arts is influenced by \
  3.     (martial_art)" for martial_art in martial_arts]
 
 
  1. print(new_phrases)
  2. ['Mixed Martial Arts is influenced by Sambo', \
  3. 'Mixed Martial Arts is influenced by Muay Thai', \
  4. 'Mixed Martial Arts is influenced by BJJ']

06 中級主題

有了這些基礎(chǔ)知識后,重要的是不僅要了解如何創(chuàng)建代碼,還要了解如何創(chuàng)建可維護(hù)的代碼。創(chuàng)建可維護(hù)代碼的一種方法是創(chuàng)建一個庫,另一種方法是使用已經(jīng)安裝的第三方庫編寫的代碼。其總體思想是最小化和分解復(fù)雜性。

  • 使用Python編寫庫

使用Python編寫庫非常重要,之后將該庫導(dǎo)入項(xiàng)目無須很長時間。下面這些示例是編寫庫的基礎(chǔ)知識:在存儲庫中有一個名為funclib的文件夾,其中有一個_init_ .py文件。要創(chuàng)建庫,在該目錄中需要有一個包含函數(shù)的模塊。

首先創(chuàng)建一個文件。

 
 
  1. touch funclib/funcmod.py

然后在該文件中創(chuàng)建一個函數(shù)。

 
 
  1. """This is a simple module"""
  2. def list_of_belts_in_bjj():
  3.     """Returns a list of the belts in Brazilian jiu-jitsu"""
  4.     belts= ["white", "blue", "purple", "brown", "black"]
  5.     return belts
 
 
  1. import sys;sys.path.append("..")
  2. from funclib import funcmod
  3. funcmod.list_of_belts_in-bjj()
  4. #輸出:['white', 'blue', 'purple', 'brown', 'black']
  • 導(dǎo)入庫

如果庫是上面的目錄,則可以用Jupyter添加sys.path.append方法來將庫導(dǎo)入。接下來,使用前面創(chuàng)建的文件夾/文件名/函數(shù)名的命名空間導(dǎo)入模塊。

  • 安裝第三方庫

可使用pip install命令安裝第三方庫。請注意,conda命令(

https://conda.io/docs/user-guide/tasks/manage-pkgs.html)是pip命令的可選替代命令。如果使用conda命令,那么pip命令也會工作得很好,因?yàn)閜ip是virtualenv虛擬環(huán)境的替代品,但它也能直接安裝軟件包。

安裝pandas包。

 
 
  1. pip install pandas

另外,還可使用requirements.txt文件安裝包。

 
 
  1. > ca requirements.txt
  2. pylint
  3. pytest
  4. pytest-cov
  5. click
  6. jupyter
  7. nbval
  8. > pip install -r requirements.txt

下面是在Jupyter Notebook中使用小型庫的示例。值得指出的是,在Jupyter Notebook中創(chuàng)建程序代碼組成的巨型蜘蛛網(wǎng)很容易,而且非常簡單的解決方法就是創(chuàng)建一些庫,然后測試并導(dǎo)入這些庫。

 
 
  1. """This is a simple module"""
  2. import pandas as pd
  3. def list_of_belts_in_bjj():
  4.     """Returns a list of the belts in Brazilian jiu-jitsu"""
  5.     belts = ["white", "blue", "purple", "brown", "black"]
  6.     return belts
  7. def count_belts():
  8.     """Uses Pandas to count number of belts"""
  9.     belts = list_of_belts_in_bjj()
  10.     df = pd.Dataframe(belts)
  11.     res = df.count()
  12.     count = res.values.tolist()[0]
  13.     return count
 
 
  1. from funclib.funcmod import count_belts
 
 
  1. print(count_belts())
  2. #輸出:5

可在Jupyter Notebook中重復(fù)使用類并與類進(jìn)行交互。最簡單的類類型就是一個名稱,類的定義形式如下。

 
 
  1. class Competitor: pass

該類可實(shí)例化為多個對象。

 
 
  1. class Competitor: pass
 
 
  1. conor = Competitor()
  2. conor.name = "Conor McGregor"
  3. conor.age = 29
  4. conor.weight = 155
 
 
  1. nate = Competitor()
  2. nate.name = "Nate Diaz"
  3. nate.age = 30
  4. nate.weight = 170
 
 
  1. def print_competitor _age(object):
  2.     """Print out age statistics about a competitor"""
  3.     print(f"{object.name} is {object.age} years old")
 
 
  1. print_competitor_age(nate)
  2. #輸出:Nate Diaz is 30 years old
 
 
  1. print_competitor_age(conor)
  2. #輸出:Conor McGregor is 29 years old
  • 類和函數(shù)的區(qū)別

類和函數(shù)的主要區(qū)別包括:

  • 函數(shù)更容易解釋。
  • 函數(shù)(典型情況下)只在函數(shù)內(nèi)部具有狀態(tài),而類在函數(shù)外部保持不變的狀態(tài)。
  • 類能以復(fù)雜性為代價提供更高級別的抽象。

網(wǎng)頁題目:一文看懂Python的控制結(jié)構(gòu):For、While、If…都有了
轉(zhuǎn)載源于:http://www.dlmjj.cn/article/djioghh.html