Python学习笔记:19个pythonic编程习惯,让你的Python入门更优雅

论坛 期权论坛 期权     
阿甘琐记   2019-7-13 17:57   1542   0
Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。

要写出 Pythonic(优雅的、地道的、整洁的)代码,需要多看多学大牛们写的代码,github 上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,下面列举一些常见的Pythonic写法。都是课堂上Python学习笔记的精华!


0. 程序必须先让人读懂,然后才能让计算机执行。
“Programs must be written for people to read, and only incidentally for machines to execute.”
[h1]1. 交换赋值[/h1]
  1. ##不推荐
复制代码
  1. temp = aa = bb = a
复制代码
  1. [b]##推荐[/b]
复制代码
  1. a, b = b, a
复制代码
  1. # 先生成一个元组(tuple)对象,然后unpack
复制代码
[h1]2. Unpacking[/h1]
  1. [/code][img]https://201907.oss-cn-shanghai.aliyuncs.com/wc/1811847-351167f7f66411670863f81a0386811a[/img]
  2. [b]##不推荐 [/b]
  3. l = ['David', 'Pythonista', '+1-514-555-1234']
  4. first_name = l[0]
  5. last_name = l[1]
  6. phone_number = l[2]
  7. [b]##推荐 [/b]
  8. l = ['David', 'Pythonista', '+1-514-555-1234']
  9. first_name, last_name, phone_number = l
  10. [code]
复制代码
  1. [/code][h1][b][/b][/h1][h1][b][/b][/h1][h1][b]3. 使用操作符in[/b][/h1]
  2. [code]
复制代码

##不推荐
if fruit == "apple" or fruit == "orange" or fruit == "berry":
# 多次判断
##推荐
if fruit in ["apple", "orange", "berry"]:
# 使用 in 更加简洁
  1. [/code][h1][/h1][h1][b]4. 字符串操作[/b][/h1]
  2. [code]
复制代码

##不推荐
colors = ['red', 'blue', 'green', 'yellow']
result = ''
for s in colors:
     result += s
# 每次赋值都丢弃以前的字符串对象, 生成一个新对象
##推荐
colors = ['red', 'blue', 'green', 'yellow']
result = ''.join(colors)
# 没有额外的内存分配
  1. [/code][h1][/h1][h1][b][/b][/h1][h1][b]5. 字典键值列表[/b][/h1]
  2. [code]
复制代码

##不推荐
for key in my_dict.keys():
# my_dict[key] ...
##推荐
for key in my_dict:
# my_dict[key] ...
# 只有当循环中需要更改key值的情况下,我们需要使用 my_dict.keys()
# 生成静态的键值列表。
  1. [/code][h1][/h1][h1][/h1][h1]6. 字典键值判断[/h1]
  2. [code]
复制代码

##不推荐
if my_dict.has_key(key):
# ...do something with d[key]
##推荐
if key in my_dict:
# ...do something with d[key]
  1. [/code][h1][/h1][h1]7. 字典 get 和 setdefault 方法[/h1]
  2. [code]
复制代码

##不推荐
navs = {}
for (portfolio, equity, position) in data:
if portfolio not in navs:
navs[portfolio] = 0
navs[portfolio] += position * prices[equity]
##推荐
navs = {}
for (portfolio, equity, position) in data:
# 使用 get 方法
navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]
# 或者使用 setdefault 方法
navs.setdefault(portfolio, 0)
navs[portfolio] += position * prices[equity]
  1. [/code][h1][/h1][h1][b]8. 判断真伪[/b][/h1]
  2. [code]
复制代码

##不推荐
if x == True:
# ....
if len(items) != 0:
# ...
if items != []:
# ...
##推荐
if x:
# ....
if items:
# ...
  1. [/code][h1][/h1][h1][b]9. 遍历列表以及索引[/b][/h1]
  2. [code]
复制代码

##不推荐

items = 'zero one two three'.split()

# method 1
i = 0
for item in items:
     print i, item
i += 1

# method 2
for i in range(len(items)):
     print i, items

##推荐

items = 'zero one two three'.split()
for i, item in enumerate(items):
    print i, item
[h1][/h1][h1]10. 列表推导[/h1]
  1. [/code][img]https://201907.oss-cn-shanghai.aliyuncs.com/wc/1811847-351167f7f66411670863f81a0386811a[/img]
  2. [b]##不推荐 [/b]
  3. new_list = []
  4. for item in a_list:
  5.     if condition(item):
  6.          new_list.append(fn(item))
  7. [b] ##推荐[/b]
  8. new_list = [fn(item) for item in a_list if condition(item)]
  9. [h1][b]11. 列表推导-嵌套[/b][/h1]
  10. [code]
复制代码

##不推荐
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...
  1. [/code][h1][/h1][h1][b]12. 循环嵌套[/b][/h1]
  2. [code]
复制代码

##不推荐
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
  1. [/code][h1][/h1][h1][b]13. 尽量使用生成器代替列表[/b][/h1]
  2. [code]
复制代码

##不推荐
def my_range(n):
     i = 0
     result = []
     while i < n:
         result.append(fn(i))
         i += 1
     return result
# 返回列表
##推荐
def my_range(n):
i = 0
result = []
while i < n:
     yield fn(i)
# 使用生成器代替列表
i += 1
# 尽量用生成器代替列表,除非必须用到列表特有的函数。
  1. [/code][h1][/h1][h1][b]14. 中间结果尽量使用imap/ifilter代替map/filter[/b][/h1]
  2. [code]
复制代码

##不推荐
reduce(rf, filter(ff, map(mf, a_list)))
##推荐
from itertools import ifilter, imap
reduce(rf, ifilter(ff, imap(mf, a_list)))
# lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。
  1. [/code]
  2. [b]15. 使用any/all函数[/b]
  3. [code]
复制代码

##不推荐
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...
  1. [/code][h1][/h1][h1][b]16. 属性(property)[/b][/h1]
  2. [code]
复制代码

##不推荐
class Clock(object):
def __init__(self):
     self.__hour = 1
def setHour(self, hour):
     if 25 > hour > 0:
        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 > 0:
        self.__hour = hour
     else:
        raise BadHourException
def __getHour(self):
     return self.__hour
hour = property(__getHour, __setHour)
  1. [/code][h1][/h1][h1][b]17. 使用 with 处理文件打开[/b][/h1]
  2. [code]
复制代码

##不推荐
f = open("some_file.txt")
try:
     data = f.read()
     # 其他文件操作..
    finally:
f.close()
##推荐
with open("some_file.txt") as f:
d
      ata = f.read()
# 其他文件操作...
[h1]18. 使用 with 忽视异常[/h1]
  1. [/code][img]https://201907.oss-cn-shanghai.aliyuncs.com/wc/1811847-351167f7f66411670863f81a0386811a[/img]
  2. [b]##不推荐[/b]
  3. try:
  4. os.remove("somefile.txt")
  5. except OSError:
  6. pass
  7. [b]##推荐 [/b]
  8. from contextlib import ignored
  9. [h1][/h1][h1][b]19. 使用 with 处理加锁[/b][/h1]
  10. [code]
复制代码
##不推荐
import threading
lock = threading.Lock()
lock.acquire()
try:
# 互斥操作...
finally:
lock.release()
##推荐
import threading
lock = threading.Lock()
with lock:
# 互斥操作...
[code][/code]



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:
帖子:
精华:
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP