Python最大的優點之一就是文法簡潔,好的程式碼就像偽程式碼一樣,乾淨、整齊、一目了然。要寫出Pythonic(優雅的、地道的、整潔的)程式碼,需要多看多學大牛們寫的程式碼,github 上有很多非常優秀的原始碼值得閱讀,例如:requests、flask、tornado,下面列舉一些常見的Pythonic寫法。
相關學習推薦:python影片教學
#0. 程式必須先讓人讀懂,然後才能讓電腦執行。
「Programs must be written for people to read, and only incidentally for machines to execute.」
##1. 交換賦值#
##不推荐 temp = a a = b b = a ##推荐 a, b = b, a # 先生成一个元组(tuple)对象,然后unpack
2. Unpacking
##不推荐 l = ['David', 'Pythonista', '+1-514-555-1234'] first_name = l[0] last_name = l[1] phone_number = l[2] ##推荐 l = ['David', 'Pythonista', '+1-514-555-1234'] first_name, last_name, phone_number = l # Python 3 Only first, *middle, last = another_list
3. 使用運算子in
##不推荐 if fruit == "apple" or fruit == "orange" or fruit == "berry": # 多次判断 ##推荐 if fruit in ["apple", "orange", "berry"]: # 使用 in 更加简洁
4. 字串運算#
##不推荐 colors = ['red', 'blue', 'green', 'yellow'] result = '' for s in colors: result += s # 每次赋值都丢弃以前的字符串对象, 生成一个新对象 ##推荐 colors = ['red', 'blue', 'green', 'yellow'] result = ''.join(colors) # 没有额外的内存分配
5. 字典鍵值列表
##不推荐 for key in my_dict.keys(): # my_dict[key] ... ##推荐 for key in my_dict: # my_dict[key] ... # 只有当循环中需要更改key值的情况下,我们需要使用 my_dict.keys() # 生成静态的键值列表。
#6.字典鍵值判斷
##不推荐 if my_dict.has_key(key): # ...do something with d[key] ##推荐 if key in my_dict: # ...do something with d[key]
7.字典get 和setdefault 方法
##不推荐 navs = {} for (portfolio, equity, position) in data: if portfolio not in navs: navs[portfolio] = 0 navs[portfolio] += position * prices[equity] ##推荐 navs = {} for (portfolio, equity, position) in data: # 使用 get 方法 navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity] # 或者使用 setdefault 方法 navs.setdefault(portfolio, 0) navs[portfolio] += position * prices[equity]
8. 判斷真偽
##不推荐 if x == True: # .... if len(items) != 0: # ... if items != []: # ... ##推荐 if x: # .... if items: # ...
9. 遍歷清單以及索引
##不推荐 items = 'zero one two three'.split() # method 1 i = 0 for item in items: print i, item i += 1 # method 2 for i in range(len(items)): print i, items[i] ##推荐 items = 'zero one two three'.split() for i, item in enumerate(items): print i, item
10. 清單推導
##不推荐 new_list = [] for item in a_list: if condition(item): new_list.append(fn(item)) ##推荐 new_list = [fn(item) for item in a_list if condition(item)]
11. 清單推導-巢狀
##不推荐 for sub_list in nested_list: if list_condition(sub_list): for item in sub_list: if item_condition(item): # do something... ##推荐 gen = (item for sl in nested_list if list_condition(sl) \ for item in sl if item_condition(item)) for item in gen: # do something...
12. 循環巢狀#
##不推荐 for x in x_list: for y in y_list: for z in z_list: # do something for x & y ##推荐 from itertools import product for x, y, z in product(x_list, y_list, z_list): # do something for x, y, z
13. 盡量使用生成器取代清單
##不推荐 def my_range(n): i = 0 result = [] while i < n: result.append(fn(i)) i += 1 return result # 返回列表 ##推荐 def my_range(n): i = 0 result = [] while i < n: yield fn(i) # 使用生成器代替列表 i += 1 *尽量用生成器代替列表,除非必须用到列表特有的函数。
14. 中間結果盡量使用imap/ifilter取代map/filter#
##不推荐 reduce(rf, filter(ff, map(mf, a_list))) ##推荐 from itertools import ifilter, imap reduce(rf, ifilter(ff, imap(mf, a_list))) *lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。
15. 使用any/all函數
##不推荐 found = False for item in a_list: if condition(item): found = True break if found: # do something if found... ##推荐 if any(condition(item) for item in a_list): # do something if found...
16. 屬性(property)
##不推荐 class Clock(object): def __init__(self): self.__hour = 1 def setHour(self, hour): if 25 > hour > 0: self.__hour = hour else: raise BadHourException def getHour(self): return self.__hour ##推荐 class Clock(object): def __init__(self): self.__hour = 1 def __setHour(self, hour): if 25 > hour > 0: self.__hour = hour else: raise BadHourException def __getHour(self): return self.__hour hour = property(__getHour, __setHour)
17. 使用with 處理檔打開
##不推荐 f = open("some_file.txt") try: data = f.read() # 其他文件操作.. finally: f.close() ##推荐 with open("some_file.txt") as f: data = f.read() # 其他文件操作...
18. 使用with 忽略例外(僅限Python 3)
##不推荐 try: os.remove("somefile.txt") except OSError: pass ##推荐 from contextlib import ignored # Python 3 only with ignored(OSError): os.remove("somefile.txt")
19. 使用with 處理加鎖
##不推荐 import threading lock = threading.Lock() lock.acquire() try: # 互斥操作... finally: lock.release() ##推荐 import threading lock = threading.Lock() with lock: # 互斥操作...
相關推薦:
以上是掌握python 19個值得學習的程式技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6
視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)