30 個(gè) Python 的最佳實(shí)踐、小貼士和技巧!

作者?|?Erik-Jan?van?Baaren? 譯者?|?彎月,責(zé)編?|?屠敏? 出品?| CSDN(ID:CSDNnews)
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

%cd:改變當(dāng)前的工作目錄
%edit:打開編輯器,并關(guān)閉編輯器后執(zhí)行鍵入的代碼
%env:顯示當(dāng)前環(huán)境變量
%pip install [pkgs]:無需離開交互式shell,就可以安裝軟件包
%time 和 %timeit:測(cè)量執(zhí)行Python代碼的時(shí)間
pip3?install?ipython
[?expression?for?item?in?list?if?conditional?]
mylist?=?[i?for?i?in?range(10)]
print(mylist)
#?[0,?1,?2,?3,?4,?5,?6,?7,?8,?9]
squares?=?[x**2?for?x?in?range(10)]
print(squares)
#?[0,?1,?4,?9,?16,?25,?36,?49,?64,?81]
def?some_function(a):
????return?(a?+?5)?/?2
my_formula?=?[some_function(i)?for?i?in?range(10)]
print(my_formula)
#?[2,?3,?3,?4,?4,?5,?5,?6,?6,?7]
filtered?=?[i?for?i?in?range(20)?if?i%2==0]
print(filtered)
#?[0,?2,?4,?6,?8,?10,?12,?14,?16,?18]
import?sys
mylist?=?range(0,?10000)
print(sys.getsizeof(mylist))
#?48
import?sys
myreallist?=?[x?for?x?in?range(0,?10000)]
print(sys.getsizeof(myreallist))
#?87632
def?get_user(id):
????#?fetch?user?from?database
????#?....
????return?name,?birthdate
name,?birthdate?=?get_user(4)
數(shù)據(jù)類的代碼量較少
你可以比較數(shù)據(jù)類,因?yàn)閿?shù)據(jù)類提供了 __eq__ 方法
調(diào)試的時(shí)候,你可以輕松地輸出數(shù)據(jù)類,因?yàn)閿?shù)據(jù)類還提供了 __repr__ 方法
數(shù)據(jù)類需要類型提示,因此可以減少Bug的發(fā)生幾率?
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')
a?=?1
b?=?2
a,?b?=?b,?a
print?(a)
#?2
print?(b)
#?1
dict1?=?{?'a':?1,?'b':?2?}
dict2?=?{?'b':?3,?'c':?4?}
merged?=?{?**dict1,?**dict2?}
print?(merged)
#?{'a':?1,?'b':?3,?'c':?4}
mystring?=?"10?awesome?python?tricks"
print(mystring.title())
'10?Awesome?Python?Tricks'
mystring?=?"The?quick?brown?fox"
mylist?=?mystring.split('?')
print(mylist)
#?['The',?'quick',?'brown',?'fox']
mylist?=?['The',?'quick',?'brown',?'fox']
mystring?=?"?".join(mylist)
print(mystring)
#?'The?quick?brown?fox'

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:'
a[start:stop:step]
start:0
end:字符串的結(jié)尾
step:1
#?We?can?easily?create?a?new?list?from?
#?the?first?two?elements?of?a?list:
first_two?=?[1,?2,?3,?4,?5][0:2]
print(first_two)
#?[1,?2]
#?And?if?we?use?a?step?value?of?2,?
#?we?can?skip?over?every?second?number
#?like?this:
steps?=?[1,?2,?3,?4,?5][0:5:2]
print(steps)
#?[1,?3,?5]
#?This?works?on?strings?too.?In?Python,
#?you?can?treat?a?string?like?a?list?of
#?letters:
mystring?=?"abcdefdn?nimt"[::2]
print(mystring)
#?'aced?it'
revstring?=?"abcdefg"[::-1]
print(revstring)
#?'gfedcba'
revarray?=?[1,?2,?3,?4,?5][::-1]
print(revarray)
#?[5,?4,?3,?2,?1]
pip3?install?Pillow

from?PIL?import?Image
im?=?Image.open("kittens.jpg")
im.show()
print(im.format,?im.size,?im.mode)
#?JPEG?(1920,?1357)?RGB
map(function,?something_iterable)
def?upper(s):
????return?s.upper()
mylist?=?list(map(upper,?['sentence',?'fragment']))
print(mylist)
#?['SENTENCE',?'FRAGMENT']
#?Convert?a?string?representation?of
#?a?number?into?a?list?of?ints.
list_of_ints?=?list(map(int,?"1234567")))
print(list_of_ints)
#?[1,?2,?3,?4,?5,?6,?7]
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'}
test?=?[1,?2,?3,?4,?2,?2,?3,?1,?4,?4,?4]
print(max(set(test),?key?=?test.count))
#?4
max() 會(huì)返回列表的最大值。參數(shù) key 會(huì)接受一個(gè)參數(shù)函數(shù)來自定義排序,在本例中為 test.count。該函數(shù)會(huì)應(yīng)用于迭代對(duì)象的每一項(xiàng)。
test.count 是 list 的內(nèi)置函數(shù)。它接受一個(gè)參數(shù),而且還會(huì)計(jì)算該參數(shù)的出現(xiàn)次數(shù)。因此,test.count(1) 將返回2,而 test.count(4) 將返回4。
set(test) 將返回 test 中所有的唯一值,也就是 {1, 2, 3, 4}。
pip3?install?progress
from?progress.bar?import?Bar
bar?=?Bar('Processing',?max=20)
for?i?in?range(20):
????#?Do?some?work
????bar.next()
bar.finish()
In?[1]:?3?*?3
Out[1]:?9In?[2]:?_?+?3
Out[2]:?12
python3?-m?http.server
s1?=?"""Multi?line?strings?can?be?put
????????between?triple?quotes.?It's?not?ideal
????????when?formatting?your?code?though"""
print?(s1)
#?Multi?line?strings?can?be?put
#?????????between?triple?quotes.?It's?not?ideal
#?????????when?formatting?your?code?though
s2?=?("You?can?also?concatenate?multiple\n"?+
????????"strings?this?way,?but?you'll?have?to\n"
????????"explicitly?put?in?the?newlines")
print(s2)
#?You?can?also?concatenate?multiple
#?strings?this?way,?but?you'll?have?to
#?explicitly?put?in?the?newlines
[on_true]?if?[expression]?else?[on_false]
x?=?"Success!"?if?(y?==?2)?else?"Failed!"
from?collections?import?Counter
mylist?=?[1,?1,?2,?3,?4,?5,?5,?5,?6,?6]
c?=?Counter(mylist)
print(c)
#?Counter({1:?2,?2:?1,?3:?1,?4:?1,?5:?3,?6:?2})
#?And?it?works?on?strings?too:
print(Counter("aaaaabbbbbccccc"))
#?Counter({'a':?5,?'b':?5,?'c':?5})
x?=?10
#?Instead?of:
if?x?>?5?and?x?15:
????print("Yes")
#?yes
#?You?can?also?write:
if?5?15:
????print("Yes")
#?Yes

from?colorama?import?Fore,?Back,?Style
print(Fore.RED?+?'some?red?text')
print(Back.GREEN?+?'and?with?a?green?background')
print(Style.DIM?+?'and?in?dim?text')
print(Style.RESET_ALL)
print('back?to?normal?now')
pip3?install?python-dateutil?
from?dateutil.parser?import?parse
logline?=?'INFO?2020-01-01T00:00:01?Happy?new?year,?human.'
timestamp?=?parse(log_line,?fuzzy=True)
print(timestamp)
#?2020-01-01?00:00:01

#?Python?2
5?/?2?=?2
5?/?2.0?=?2.5
Python?3
5?/?2?=?2.5
5?//?2?=?2
pip?install?chardet
chardetect?somefile.txt
somefile.txt:?ascii?with?confidence?1.0
評(píng)論
圖片
表情
