If you have fast machine and recent Google Chrome or Safari installed, please check a bit more "moving" version of that presentation

Otherwise, scroll down to see the slides

符合语言习惯的Python编程

Programs must be written for people to read, and only incidentally for machines to execute.

程序必须先让人读懂,然后才能让计算机执行。

- Abelson & Sussman

PEP 8: Style Guide for Python Code

http://www.python.org/dev/peps/pep-0008/

交换赋值

temp = a
a = b
b = a  
a, b = b, a  #  先生成一个元组(tuple)对象,然后unpack  

Unpacking

l = ['David', 'Pythonista', '+1-514-555-1234']
first_name = l[0]
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  

使用操作符in

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]  

字典 get 和 setdefault 方法

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]

判断真伪

if x == True:
    # ....
if len(items) != 0:
    # ...
if items != []:
    # ...  
if x:
    # ....
if items:
    # ...  

遍历列表以及索引

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[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 = 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

*尽量用生成器代替列表,除非必须用到列表特有的函数。

中间结果尽量使用imap/ifilter代替map/filter

reduce(rf, filter(ff, map(mf, a_list)))
from itertools import ifilter, imap
reduce(rf, ifilter(ff, imap(mf, a_list)))

*lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。

使用any/all函数

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...  

属性(property)

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)

使用 with 处理文件打开

f = open("some_file.txt")
try:
    data = f.read()
    # 其他文件操作..
finally:
    f.close()
with open("some_file.txt") as f:
    data = f.read()
    # 其他文件操作...

使用 with 忽视异常(仅限Python 3)

try:
    os.remove("somefile.txt")
except OSError:
    pass
from contextlib import ignored  # Python 3 only

with ignored(OSError):
    os.remove("somefile.txt")

使用 with 处理加锁

import threading
lock = threading.Lock()

lock.acquire()
try:
    # 互斥操作...
finally:
    lock.release()
import threading
lock = threading.Lock()

with lock:
    # 互斥操作...

参考

谢谢 !

Use a spacebar or arrow keys to navigate