18個(gè)好用的Python技巧分享(建議收藏)
處理用戶(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)
處理多個(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.")
判斷數(shù)字奇偶性
這很容易實(shí)現(xiàn),我們從用戶(hù)那里得到輸入,將其轉(zhuǎn)換為整數(shù),檢查 對(duì)數(shù)字2的求余操作,如果余數(shù)為零,則它是偶數(shù)。
print('odd' if int(input('Enter a number: '))%2 else 'even')
交換變量
在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
判斷字符串是否為回文串
將字符串進(jìn)行反轉(zhuǎn)最簡(jiǎn)單的實(shí)現(xiàn)方式為 [::-1] ,代碼如下:
print("John Deo"[::-1])
反轉(zhuǎn)字符串
在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
盡量使用 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")
刪除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)
找到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)
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)
使用*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))
在循環(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)
拼接list中多個(gè)元素
在Python中一般使用Join() 函數(shù)來(lái)將list中所有元素拼接到一起,當(dāng)然我們也可以在拼接的時(shí)候添加拼接符號(hào),樣例如下:
names = ["john", "sara", "jim", "rock"] print(", ".join(names))
將兩個(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}
使用兩個(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))
字典按照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))
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'}
可見(jiàn)使用pprint函數(shù)可以讓字典的輸出更加容易閱讀
反轉(zhuǎn)列表
Python 中通常有兩種反轉(zhuǎn)列表的方法:切片或 reverse() 函數(shù)調(diào)用。這兩種方法都可以反轉(zhuǎn)列表,但需要注意的是內(nèi)置函數(shù) reverse() 會(huì)更改原始列表,而切片方法會(huì)創(chuàng)建一個(gè)新列表。
但是他們的表現(xiàn)呢?哪種方式更有效?讓我們看一下下面的例子:
# 使用切片 $ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist[::-1]' 1000000 loops, best of 5: 15.6 usec per loop # 使用reverse() $ python -m timeit -n 1000000 -s 'import numpy as np' 'mylist=list(np.arange(0, 200))' 'mylist.reverse()' 1000000 loops, best of 5: 10.7 usec per loop
這兩種方法都可以反轉(zhuǎn)列表,但需要注意的是內(nèi)置函數(shù) reverse() 會(huì)更改原始列表,而切片方法會(huì)創(chuàng)建一個(gè)新列表。
顯然,內(nèi)置函數(shù) reverse() 比列表切片方法更快!
到此這篇關(guān)于18個(gè)好用的Python技巧分享(建議收藏)的文章就介紹到這了,更多相關(guān)Python技巧內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pytorch mask-rcnn 實(shí)現(xiàn)細(xì)節(jié)分享
這篇文章主要介紹了Pytorch mask-rcnn 實(shí)現(xiàn)細(xì)節(jié)分享,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06關(guān)于ResNeXt網(wǎng)絡(luò)的pytorch實(shí)現(xiàn)
今天小編就為大家分享一篇關(guān)于ResNeXt網(wǎng)絡(luò)的pytorch實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01Python數(shù)組拼接np.concatenate實(shí)現(xiàn)過(guò)程
這篇文章主要介紹了Python數(shù)組拼接np.concatenate實(shí)現(xiàn)過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04spark?dataframe全局排序id與分組后保留最大值行
這篇文章主要為大家介紹了spark?dataframe全局排序id與分組后保留最大值行實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02