本文整理了Python的10個小技巧[1].文章參考了30 Python Best Practices, Tips, And Tricks.有些技巧或建議挺不錯的。
更多內(nèi)容可以關(guān)注個人博客
1. 檢查Python的最低版本的方法
你可以在代碼中檢查Python的版本,以確保別人正常運行你的代碼。
import sys
if not sys.version_info > (2, 7):
# berate your user for running a 10 year
# python version
elif not sys.version_info >= (3, 5):
# Kindly tell your user (s)he needs to upgrade
# because you're using 3.5 features
2. 檢查對象的內(nèi)存使用情況
直接使用sys.getsizeof函數(shù)
import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))
# 48
為什么是48bytes,這是因為range函數(shù)返回的是一個類,用起來像是列表,但是比列表更加高效的利用內(nèi)存。
可以使用列表展開式來比較內(nèi)存使用情況
import sys
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))
# 87632
3. 使用數(shù)據(jù)類
自從Python3.7以后,提供了數(shù)據(jù)類data classes.相比普通類有更多的優(yōu)點。
- 最少的代碼量
- 默認實現(xiàn)了
__eq__和__repr__接口,可以直接比較數(shù)據(jù)大小和打印數(shù)據(jù) - 要求類型標注,降低了代碼bug的可能性。
from dataclasses import dataclass
@dataclass
class Card:
rank: str
suit: str
card = Card("Q", "hearts")
print(card == card)
# True
print(card.rank)
# 'Q'
print(card)
Card(rank='Q', suit='hearts')
實現(xiàn)數(shù)據(jù)不可改變的數(shù)據(jù)類
from dataclasses import dataclass
@dataclass(frozen=True)
class Position:
name: str
lon: float = 0.0
lat: float = 0.0
pos = Position('Oslo', 10.8, 59.9)
print(pos.name)
pos.name = "Stockholm" # IDE直接會提示報錯
# Traceback (most recent call last):
# File "/Users/vincent/Documents/pyhome/demo2.py", line 14, in <module>
# pos.name = "Stockholm"
# File "<string>", line 3, in __setattr__
# dataclasses.FrozenInstanceError: cannot assign to field 'name'
詳細更多使用可以參考這里
4. 交換變量
有一次面試的時候碰到了這個問題。“如何在不引入第三個變量的情況下,交換兩個變量的值”。對于Python實在太友好了,一行代碼就能搞定。
a = 1
b = 2
a, b = b, a
print (a)
# 2
print (b)
# 1
5. 合并字典數(shù)據(jù)
自從Python3.5合并字典就非常的容易了。
dict1 = { 'a': 1, 'b': 2 }
dict2 = { 'b': 3, 'c': 4 }
merged = { **dict1, **dict2 }
print (merged)
# {'a': 1, 'b': 3, 'c': 4}
如果碰到重復(fù)的key,之前的key對用的值將會被覆蓋。
6. Emoji的使用
安裝emoji包
pip3 install emoji
import emoji
result = emoji.emojize('Python is :thumbs_up:')
print(result)
# 'Python is ??'
# You can also reverse this:
result = emoji.demojize('Python is ??')
print(result)
# 'Python is :thumbs_up:'
7. 反轉(zhuǎn)字符串和列表
你可以利用切片訪問的方式,實現(xiàn)反轉(zhuǎn)字符串和列表,只要將步長設(shè)為-1即可。
revstring = "abcdefg"[::-1]
print(revstring)
# 'gfedcba'
revarray = [1, 2, 3, 4, 5][::-1]
print(revarray)
# [5, 4, 3, 2, 1]
8. 從列表或字符串中獲取唯一元素(元素去重)
通過set函數(shù)創(chuàng)建一個set集合,就能實現(xiàn)元素去重。
mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
print (set(mylist))
# {1, 2, 3, 4, 5, 6}
# And since a string can be treated like a
# list of letters, you can also get the
# unique letters from a string this way:
print (set("aaabbbcccdddeeefff"))
# {'a', 'b', 'c', 'd', 'e', 'f'}
9. 找到出現(xiàn)次數(shù)最多的元素值
test = [1, 2, 5, 3, 5, 4, 2, 2, 5, 3, 1, 4, 5, 4, 5, 4, 5, 10]
print(max(set(test), key = test.count))
# 5
- set(test)返回去重以后的元素值
- max函數(shù)獲取最大值,比較的key是元素出現(xiàn)的次數(shù)
- 最終統(tǒng)計出set(test)中出現(xiàn)次數(shù)最多的元素值
10. 創(chuàng)建進度條
可以使用progress包快速創(chuàng)建進度條
pip3 install progress
from progress.bar import Bar
import time
bar = Bar('Processing', max=20)
for i in range(20):
# Do some work
time.sleep(0.2)
bar.next()
bar.finish()

1_JAQfXWEmuu-9Cvvd5LZPpg.gif