溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

有哪些好用的Python技巧

發(fā)布時(shí)間:2023-04-17 09:52:22 來(lái)源:億速云 閱讀:226 作者:iii 欄目:編程語(yǔ)言

今天小編給大家分享一下有哪些好用的Python技巧的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。

技巧總結(jié)

1、處理用戶的多個(gè)輸入

有時(shí)我們需要從用戶那里獲得多個(gè)輸入,以便使用循環(huán)或任何迭代,一般的寫法如下:

# 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、處理多個(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.")
3、 判斷數(shù)字奇偶性

這很容易實(shí)現(xiàn),我們從用戶那里得到輸入,將其轉(zhuǎn)換為整數(shù),檢查 對(duì)數(shù)字2的求余操作,如果余數(shù)為零,則它是偶數(shù)。

print('odd' if int(input('Enter a number: '))%2 else 'even')
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
5、 判斷字符串是否為回文串

將字符串進(jìn)行反轉(zhuǎn)最簡(jiǎn)單的實(shí)現(xiàn)方式為 [::-1] ,代碼如下:

print("John Deo"[::-1])
6、 反轉(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
7、 盡量使用 Inline if statement

大多數(shù)情況下,我們?cè)跅l件之后只有一個(gè)語(yǔ)句,因此使用Inline if statement 可以幫助我們編寫更簡(jiǎn)潔的代碼。舉例如下,一般的寫法為:

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")
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)
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)
10、 list 生成式

Python中我最喜歡的功能就是list comprehensions , 這個(gè)特性可以使我們編寫非常簡(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)
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))
12、 在循環(huán)時(shí)處理下標(biāo)

有時(shí)我們?cè)诠ぷ髦?想要獲得循環(huán)中元素的下標(biāo),一般來(lái)說(shuō),比較優(yōu)雅的寫法如下:

lst = ["blue", "lightblue", "pink", "orange", "red"]
for idx, item in enumerate(lst):
print(idx, item)
13、 拼接list中多個(gè)元素

在Python中一般使用Join() 函數(shù)來(lái)將list中所有元素拼接到一起,當(dāng)然我們也可以在拼接的時(shí)候添加拼接符號(hào),樣例如下:

names = ["john", "sara", "jim", "rock"]
print(", ".join(names))
14、 將兩個(gè)字典進(jìn)行合并

另外,搜索公眾號(hào)頂級(jí)Python后臺(tái)回復(fù)“進(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}
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))
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))
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'}

以上就是“有哪些好用的Python技巧”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI