您好,登錄后才能下訂單哦!
小編給大家分享一下Python中常見的Pythonic寫法有哪些,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
“Programs must be written for people to read, and only incidentally for machines to execute.”
##不推薦
temp = a
a = b
b = a
##推薦
a, b = b, a # 先生成一個元組(tuple)對象,然后unpack
##不推薦
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name = l[]
last_name = l[1]
phone_number = l[2]
##推薦
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name, last_name, phone_number = l
# Python 3 Only
first, *middle, last = another_list
##不推薦
if fruit == "apple" or fruit == "orange" or fruit == "berry":
# 多次判斷
##推薦
if fruit in ["apple", "orange", "berry"]:
# 使用 in 更加簡潔
##不推薦
colors = ['red', 'blue', 'green', 'yellow']
result = ''
for s in colors:
result += s # 每次賦值都丟棄以前的字符串對象, 生成一個新對象
##推薦
colors = ['red', 'blue', 'green', 'yellow']
result = ''.join(colors) # 沒有額外的內存分配
##不推薦
for key in my_dict.keys():
# my_dict[key] ...
##推薦
for key in my_dict:
# my_dict[key] ...
# 只有當循環中需要更改key值的情況下,我們需要使用 my_dict.keys()
# 生成靜態的鍵值列表。
##不推薦
if my_dict.has_key(key):
# ...do something with d[key]
##推薦
if key in my_dict:
# ...do something with d[key]
##不推薦
navs = {}
for (portfolio, equity, position) in data:
if portfolio not in navs:
navs[portfolio] =
navs[portfolio] += position * prices[equity]
##推薦
navs = {}
for (portfolio, equity, position) in data:
# 使用 get 方法
navs[portfolio] = navs.get(portfolio, ) + position * prices[equity]
# 或者使用 setdefault 方法
navs.setdefault(portfolio, )
navs[portfolio] += position * prices[equity]
##不推薦
if x == True:
# ....
if len(items) != :
# ...
if items != []:
# ...
##推薦
if x:
# ....
if items:
# ...
##不推薦
items = 'zero one two three'.split()
# method 1
i =
for item in items:
print i, item
i += 1
# method 2
for i in range(len(items)):
print i, items[i]
##推薦
items = 'zero one two three'.split()
for i, item in enumerate(items):
print i, item
##不推薦
new_list = []
for item in a_list:
if condition(item):
new_list.append(fn(item))
##推薦
new_list = [fn(item) for item in a_list if condition(item)]
##不推薦
for sub_list in nested_list:
if list_condition(sub_list):
for item in sub_list:
if item_condition(item):
# do something...
##推薦
gen = (item for sl in nested_list if list_condition(sl) \
for item in sl if item_condition(item))
for item in gen:
# do something...
##不推薦
for x in x_list:
for y in y_list:
for z in z_list:
# do something for x & y
##推薦
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
# do something for x, y, z
##不推薦
def my_range(n):
i =
result = []
while i < n:
result.append(fn(i))
i += 1
return result # 返回列表
##推薦
def my_range(n):
i =
result = []
while i < n:
yield fn(i) # 使用生成器代替列表
i += 1
*盡量用生成器代替列表,除非必須用到列表特有的函數。
##不推薦
reduce(rf, filter(ff, map(mf, a_list)))
##推薦
from itertools import ifilter, imap
reduce(rf, ifilter(ff, imap(mf, a_list)))
*lazy evaluation 會帶來更高的內存使用效率,特別是當處理大數據操作的時候。
##不推薦
found = False
for item in a_list:
if condition(item):
found = True
break
if found:
# do something if found...
##推薦
if any(condition(item) for item in a_list):
# do something if found...
##不推薦
class Clock(object):
def __init__(self):
self.__hour = 1
def setHour(self, hour):
if 25 > hour > : self.__hour = hour
else: raise BadHourException
def getHour(self):
return self.__hour
##推薦
class Clock(object):
def __init__(self):
self.__hour = 1
def __setHour(self, hour):
if 25 > hour > : self.__hour = hour
else: raise BadHourException
def __getHour(self):
return self.__hour
hour = property(__getHour, __setHour)
##不推薦
f = open("some_file.txt")
try:
data = f.read()
# 其他文件操作..
finally:
f.close()
##推薦
with open("some_file.txt") as f:
data = f.read()
# 其他文件操作...
##不推薦
try:
os.remove("somefile.txt")
except OSError:
pass
##推薦
from contextlib import ignored # Python 3 only
with ignored(OSError):
os.remove("somefile.txt")
##不推薦
import threading
lock = threading.Lock()
lock.acquire()
try:
# 互斥操作...
finally:
lock.release()
##推薦
import threading
lock = threading.Lock()
with lock:
# 互斥操作...
以上是“Python中常見的Pythonic寫法有哪些”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。