成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

一文看懂Python的控制結構:For、While、If…都有了

開發 后端
傳統Python語言的主要控制結構是for循環。然而,需要注意的是for循環在Pandas中不常用,因此Python中for循環的有效執行并不適用于Pandas模式。

 [[331673]]

 

傳統Python語言的主要控制結構是for循環。然而,需要注意的是for循環在Pandas中不常用,因此Python中for循環的有效執行并不適用于Pandas模式。一些常見控制結構如下。

  • for循環
  • while循環
  • if/else語句
  • try/except語句
  • 生成器表達式
  • 列表推導式
  • 模式匹配

所有的程序最終都需要一種控制執行流的方式。本節介紹一些控制執行流的技術。

01 for循環

for循環是Python的一種最基本的控制結構。使用for循環的一種常見模式是使用range函數生成數值范圍,然后對其進行迭代。

 

  1. res = range(3) 
  2. print(list(res)) 
  3.  
  4. #輸出:[0, 1, 2] 

 

  1. for i in range(3): 
  2. print(i) 
  3.  
  4. '''輸出: 
  5. ''
  • for循環列表

使用for循環的另一種常見模式是對列表進行迭代。

 

  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. '''輸出: 
  7. Sambo has influenced modern mixed martial arts 
  8. Muay Thai has influenced modern mixed martial arts 
  9. BJJ has influenced modern mixed martial arts 
  10. ''

02 while循環

while循環是一種條件有效就會重復執行的循環方式。while循環的常見用途是創建無限循環。在本示例中,while循環用于過濾函數,該函數返回兩種攻擊類型中的一種。

 

  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 forcount}") 
  17.  
  18. '''輸出: 
  19. There are a total of 3 attacks coming! 
  20. crossing legs to prevent attack #1 
  21. crossing legs to prevent attack #2 
  22. This is not a lower body attack, I will cross my arms for #3 
  23. ''

03 if/else語句

if/else語句是一條在判斷之間進行分支的常見語句。在本示例中,if/elif用于匹配分支。如果沒有匹配項,則執行最后一條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.  
  3. #輸出:You're on your own, there is no suggestion for an attack 

04 生成器表達式

生成器表達式建立在yield語句的概念上,它允許對序列進行惰性求值。生成器表達式的益處是,在實際求值計算前不會對任何內容進行求值或將其放入內存。這就是下面的示例可以在生成的無限隨機攻擊序列中執行的原因。

在生成器管道中,諸如 “arm_triangle”的小寫攻擊被轉換為“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.  
  13. #Make all attacks appear as Upper Case 
  14. upper_case_attacks = \ 
  15.          (attack.pop().upper() for attack in \ 
  16.          lazy_return_random_attacks()) 

 

  1. next(upper-case_attacks) 
  2.  
  3. #輸出: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.  
  3. #輸出:'STRAIGHT ANKLE LOCK' 

 

  1. for number in range(10): 
  2.     print(next(new_attack_phrase)) 
  3.  
  4. '''輸出: 
  5. KIMURA 
  6. KEYLOCK 
  7. STRAIGHT ANKLE LOCK 
  8. ''

05 列表推導式

語法上列表推導式與生成器表達式類似,然而直接對比它們,會發現列表推導式是在內存中求值。此外,列表推導式是優化的C代碼,可以認為這是對傳統for循環的重大改進。

 

  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 中級主題

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

  • 使用Python編寫庫

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

首先創建一個文件。

 

  1. touch funclib/funcmod.py 

然后在該文件中創建一個函數。

 

  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.  
  5. #輸出:['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包。

 

  1. pip install pandas 

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

 

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

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

 

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

 

  1. from funclib.funcmod import count_belts 

 

  1. print(count_belts()) 
  2.  
  3. #輸出:5 

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

 

  1. class Competitor: pass 

該類可實例化為多個對象。

 

  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.  
  4.     print(f"{object.name} is {object.age} years old"

 

  1. print_competitor_age(nate) 
  2.  
  3. #輸出:Nate Diaz is 30 years old 

 

  1. print_competitor_age(conor) 
  2.  
  3. #輸出:Conor McGregor is 29 years old 
  • 類和函數的區別

類和函數的主要區別包括:

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

 

責任編輯:華軒 來源: 今日頭條
相關推薦

2019-07-01 09:22:15

Linux操作系統硬件

2024-10-10 17:55:57

LinuxACL訪問控制列表

2020-03-31 14:40:24

HashMap源碼Java

2019-05-22 09:50:42

Python沙箱逃逸網絡攻擊

2016-08-18 00:21:12

網絡爬蟲抓取網絡

2019-09-03 10:40:23

數據結構HTML編程

2024-08-12 12:30:27

2019-05-08 15:02:11

Android 10安卓谷歌

2023-07-14 08:00:00

ORMRust ORMSQL

2021-08-02 06:56:19

TypeScript編程語言編譯器

2025-01-20 09:15:00

iOS 18.3蘋果iOS 18

2017-07-28 09:11:14

HIVEHBASE區別

2018-05-31 09:46:04

車聯網智能交通ITS

2025-05-20 13:52:12

GPU集群微軟

2025-03-25 09:06:11

2021-05-11 10:40:29

JUCAQSJava

2021-05-12 15:16:17

JUCAQSJava

2021-02-21 11:25:17

云計算IaaSPaaS

2022-04-26 13:41:16

區塊鏈比特幣數據庫

2023-04-10 11:35:31

評估模型業務流程
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: www.一区二区 | 91精品综合久久久久久五月天 | 亚洲精品专区 | 免费成人高清在线视频 | 欧美精品一区二区三区在线播放 | 日韩av手机在线观看 | 一区二区三区在线播放视频 | 色吧久久 | 国产成人午夜精品影院游乐网 | 欧美综合在线观看 | 亚洲黄色一级毛片 | 超碰成人在线观看 | 日韩欧美在线视频一区 | 国产网站久久 | 欧美亚洲视频在线观看 | 水蜜桃亚洲一二三四在线 | 国产精品久久久久久久久免费高清 | av免费成人| 欧美激情一区二区 | 亚洲国产精品一区二区第一页 | 午夜免费看 | 欧美在线视频一区二区 | www中文字幕 | 日韩有码在线观看 | 日本成人区 | 亚洲一区二区中文字幕 | 97超碰站 | 成人午夜免费网站 | 成人欧美一区二区 | 免费中文字幕日韩欧美 | 不卡一二区 | 日韩免费一区 | 91大片 | 日韩成人免费视频 | 亚洲精品片 | 一级黄色裸片 | 日韩一区二区三区在线观看 | 久久久国产精品 | 精品久久久精品 | 日韩中文字幕在线视频 | 国产精品1区2区3区 国产在线观看一区 |