17條提高工作效率的Python技巧分享
1.引言
在這篇文章中,我們將討論最常用的python技巧。大多數(shù)這些技巧都是我在日常工作中使用過(guò)的簡(jiǎn)單的Trick,我覺(jué)得好東西就是要拿出來(lái)和大家一起分享。
2.技巧總結(jié)
2.1.處理用戶(hù)的多個(gè)輸入
有時(shí)我們需要從用戶(hù)那里獲得多個(gè)輸入,以便使用循環(huán)或任何迭代,一般的寫(xiě)法如下:
# bad practice碼 n1 = input("enter a number : ") n2 = input("enter a number : ") n2 = input("enter a number : ") print(n1, n2, n3)
但是更好的處理方法如下:
# good practice n1, n2, n3 = input("enter a number : ").split() print(n1, n2, n3)
2.2.處理多個(gè)條件語(yǔ)句
如果我們?cè)诖a中需要檢查多個(gè)條件語(yǔ)句,此時(shí)我們可以使用 all() 或 any() 函數(shù)來(lái)實(shí)現(xiàn)我們的目標(biāo)。一般來(lái)說(shuō), 當(dāng)我們有多個(gè) and 條件時(shí)使用 all(),當(dāng)我們有多個(gè) or 條件時(shí)使用 any()。這種用法將使我們的代碼更加清晰易讀,可以方便我們?cè)谡{(diào)試時(shí)不會(huì)遇到麻煩。
對(duì)于all()的一般例子如下:
size = "lg" color = "blue" price = 50 # bad practice if size == "lg" and color == "blue" and price < 100: ? ? print("Yes, I want to but the product.")
更好的處理方法如下:
# good practice conditions = [ ? ? size == "lg", ? ? color == "blue", ? ? price < 100, ] if all(conditions): ? ? print("Yes, I want to but the product.")
對(duì)于any()的一般例子如下:
# bad practice size = "lg" color = "blue" price = 50 if size == "lg" or color == "blue" or price < 100: ? ? print("Yes, I want to but the product.")
更好的處理方法如下:
# good practice conditions = [ ? ? size == "lg", ? ? color == "blue", ? ? price < 100, ] if any(conditions): ? ? print("Yes, I want to but the product.")
2.3.判斷數(shù)字奇偶性
這很容易實(shí)現(xiàn),我們從用戶(hù)那里得到輸入,將其轉(zhuǎn)換為整數(shù),檢查 對(duì)數(shù)字2的求余操作,如果余數(shù)為零,則它是偶數(shù)。
print('odd' if int(input('Enter a number: '))%2 else 'even')
2.4.交換變量
在Python
中如果需要交換變量的值,我們無(wú)需定義臨時(shí)變量來(lái)操作。
我們一般使用如下代碼來(lái)實(shí)現(xiàn)變量交換:
v1 = 100 v2 = 200 # bad practice temp = v1 v1 = v2 v2 = temp
但是更好的處理方法如下:
v1 = 100 v2 = 200 # good practice v1, v2 = v2, v1
2.5.反轉(zhuǎn)字符串
將字符串進(jìn)行反轉(zhuǎn)最簡(jiǎn)單的實(shí)現(xiàn)方式為[::-1] ,代碼如下:
print("John Deo"[::-1])
2.6.判斷字符串是否為回文串
在Python中判斷一個(gè)字符串是否為回文串,只需要使用語(yǔ)句 string.find(string[::-1])== 0
,示
例代碼如下:
v1 = "madam" # is a palindrome string v2 = "master" # is not a palindrome string print(v1.find(v1[::-1]) == 0) # True print(v1.find(v2[::-1]) == 0) # False
2.7.盡量使用 Inline if statement
大多數(shù)情況下,我們?cè)跅l件之后只有一個(gè)語(yǔ)句,因此使用Inline if statement 可以幫助我們編寫(xiě)更簡(jiǎn)潔的代碼。
舉例如下,一般的寫(xiě)法為:
name = "ali" age = 22 # bad practices if name: ? ? print(name) if name and age > 18: ? ? print("user is verified")
但是更好的處理方法如下:
# a better approach print(name if name else "") """ here you have to define the else condition too""" # good practice? name and print(name) age > 18 and name and print("user is verified")
2.8.刪除list中的重復(fù)元素
我們不需要遍歷整個(gè)list列表來(lái)檢查重復(fù)元素,我們可以簡(jiǎn)單地使用 set() 來(lái)刪除重復(fù)元素,
代碼如下:
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0] print(lst) unique_lst = list(set(lst)) print(unique_lst)
2.9.找到list中重復(fù)最多的元素
在Python中可以使用 max( )
函數(shù)并傳遞list.count
作為key,即可找出列表list中重復(fù)次數(shù)最多的元素,代碼如下:
lst = [1, 2, 3, 4, 3, 4, 4, 5, 6, 3, 1, 6, 7, 9, 4, 0] most_repeated_item = max(lst, key=lst.count) print(most_repeated_item)
2.10.list 生成式
Python中我最喜歡的功能就是list comprehensions
, 這個(gè)特性可以使我們編寫(xiě)非常簡(jiǎn)潔功能強(qiáng)大的代碼,而且這些代碼讀起來(lái)幾乎像自然語(yǔ)言一樣通俗易懂。
舉例如下:
numbers = [1,2,3,4,5,6,7] evens = [x for x in numbers if x % 2 is 0] odds = [y for y in numbers if y not in evens] cities = ['London', 'Dublin', 'Oslo'] def visit(city): ? ? print("Welcome to "+city) for city in cities: ? ? visit(city)
2.11.使用*args傳遞多個(gè)參數(shù)
在Python中我們可以使用*args來(lái)向函數(shù)傳遞多個(gè)參數(shù),舉例如下:
def sum_of_squares(n1, n2) ? ? return n1**2 + n2**2 print(sum_of_squares(2,3)) # output: 13 """ what ever if you want to pass, multiple args to the function? as n number of args. so let's make it dynamic. """? def sum_of_squares(*args): ? ? return sum([item**2 for item in args]) # now you can pass as many parameters as you want print(sum_of_squares(2, 3, 4)) print(sum_of_squares(2, 3, 4, 5, 6))
2.12.在循環(huán)時(shí)處理下標(biāo)
有時(shí)我們?cè)诠ぷ髦?想要獲得循環(huán)中元素的下標(biāo),一般來(lái)說(shuō),比較優(yōu)雅的寫(xiě)法如下:
lst = ["blue", "lightblue", "pink", "orange", "red"] for idx, item in enumerate(lst): ? ? ?print(idx, item)
2.13.拼接list中多個(gè)元素
在Python中一般使用Join()
函數(shù)來(lái)將list中所有元素拼接到一起,當(dāng)然我們也可以在拼接的時(shí)候添加拼接符號(hào)
樣例如下:
names = ["john", "sara", "jim", "rock"] print(", ".join(names))
2.14.將兩個(gè)字典進(jìn)行合并
在Python中我們可以使用{**dict_name, **dict_name2, … }
將多個(gè)字典進(jìn)行合并,
樣例如下:
d1 = {"v1": 22, "v2": 33} d2 = {"v2": 44, "v3": 55} d3 = {**d1, **d2} print(d3)
結(jié)果如下:
{'v1': 22, 'v2': 44, 'v3': 55}
2.15.使用兩個(gè)list生成一個(gè)字典
在Python中,如果我們需要將兩個(gè)列表中對(duì)應(yīng)的元素組成字典,那么我們可以使用 zip 功能來(lái)方便地做到這一點(diǎn)。
代碼如下:
keys = ['a', 'b', 'c'] vals = [1, 2, 3] zipped = dict(zip(keys, vals))
2.16.字典按照value進(jìn)行排序
在Python中我們使用sorted()
函數(shù)來(lái)按照字典的value來(lái)對(duì)其進(jìn)行排序.
代碼如下:
d = { ? ? "v1": 80, ? ? "v2": 20, ? ? "v3": 40, ? ? "v4": 20, ? ? "v5": 10, } sorted_d = dict(sorted(d.items(), key=lambda item: item[1])) print(sorted_d)
當(dāng)然我們也可以使用itemgetter( ) 來(lái)替代上述 lambda函數(shù),
代碼如下:
from operator import itemgetter sorted_d = dict(sorted(d.items(), key=itemgetter(1)))
更進(jìn)一步,我們也可以通過(guò)傳遞reverse=True
對(duì)其進(jìn)行降序排序:
sorted_d = dict(sorted(d.items(), key=itemgetter(1), reverse=True))
2.17.Pretty print
在Python
中使用Print()
函數(shù),有時(shí)候的輸出賊拉拉丑陋,此時(shí)我們使用pprint
可以使輸出更加美觀,
樣例如下:
from pprint import pprint data = { ? ? "name": "john deo", ? ? "age": "22", ? ? "address": {"contry": "canada", "state": "an state of canada :)", "address": "street st.34 north 12"}, ? ? "attr": {"verified": True, "emialaddress": True}, } print(data) pprint(data)
輸出如下:
{'name': 'john deo', 'age': '22', 'address': {'contry': 'canada', 'state': 'an state of canada :)', 'address': 'street st.34 north 12'}, 'attr': {'verified': True, 'emialaddress': True}} {'address': {'address': 'street st.34 north 12', ? ? ? ? ? ? ?'contry': 'canada', ? ? ? ? ? ? ?'state': 'an state of canada :)'}, ?'age': '22', ?'attr': {'emialaddress': True, 'verified': True}, ?'name': 'john deo'}
使用pprint函數(shù)可以讓字典的輸出更加容易閱讀.
到此這篇關(guān)于17條提高工作效率的Python技巧分享的文章就介紹到這了,更多相關(guān)提高工作效率的Python技巧 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python多進(jìn)程程序打包成exe的問(wèn)題
這篇文章主要介紹了python多進(jìn)程程序打包成exe的問(wèn)題的相關(guān)資料,需要的朋友可以參考下2022-12-12Python中使用filter過(guò)濾列表的一個(gè)小技巧分享
這篇文章主要介紹了Python中使用filter過(guò)濾列表的一個(gè)小技巧分享,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05Python統(tǒng)計(jì)時(shí)間內(nèi)的并發(fā)數(shù)代碼實(shí)例
這篇文章主要介紹了Python統(tǒng)計(jì)時(shí)間內(nèi)的并發(fā)數(shù)代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12一文搞懂Python中Pandas數(shù)據(jù)合并
pandas是基于NumPy的一種工具,該工具是為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建的。Pandas納入了大量庫(kù)和一些標(biāo)準(zhǔn)的數(shù)據(jù)模型,提供了高效操作大型數(shù)據(jù)集的工具。pandas提供大量快速便捷地處理數(shù)據(jù)的函數(shù)和方法。你很快就會(huì)發(fā)現(xiàn),它是使Python強(qiáng)大而高效的數(shù)據(jù)分析環(huán)境的重要因素之一2021-11-11pytorch geometric的GNN、GCN的節(jié)點(diǎn)分類(lèi)方式
這篇文章主要介紹了pytorch geometric的GNN、GCN的節(jié)點(diǎn)分類(lèi)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12python 判斷文件還是文件夾的簡(jiǎn)單實(shí)例
今天小編就為大家分享一篇python 判斷文件還是文件夾的簡(jiǎn)單實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06python通過(guò)colorama模塊在控制臺(tái)輸出彩色文字的方法
這篇文章主要介紹了python通過(guò)colorama模塊在控制臺(tái)輸出彩色文字的方法,實(shí)例分析了colorama模塊的功能及相關(guān)使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03