Python编程技巧
1.交换赋值
a, b = b, a;
2.Unpacking
l = ["a", "b", "c"];
a, b, c = l;
a, *midList, c = l;
3.使用操作符in
if t in ["a", "b", "c"]:
4.字符串操作
l = ['a', 'b', 'c', 'd']
result = ''.join(l)
5.字典键值列表
for key in my_dict.keys():
for key in my_dict:
6.字典键值判断
if my_dict.has_key(key):
if key in my_dict:
7.字典 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:
navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]
navs.setdefault(portfolio, 0)
navs[portfolio] += position * prices[equity]
8.判断真伪
if x == True:
if len(items) != 0:
if items != []:
if x:
if items:
9.遍历列表以及索引
items = 'zero one two three'.split()
i = 0
for item in items:
print(i, item)
i += 1
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)
10.列表推导
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)]
11.列表推导-嵌套
for sub_list in nested_list:
if list_condition(sub_list):
for item in sub_list:
if item_condition(item):
gen = (item for sl in nested_list if list_condition(sl) for item in sl if item_condition(item))
for item in gen:
12.循环嵌套
for x in x_list:
for y in y_list:
for z in z_list:
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
13.尽量使用生成器代替列表
def my_range(n):
i = 0
result = []
while i < n:
result.append(fn(i))
i += 1
return result
for res in my_range(10):
def my_range(n):
i = 0
while i < n:
yield fn(i)
i += 1
for res in my_range(10):
14.中间结果尽量使用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)))
15.使用any/all函数
found = False
for item in a_list:
if condition(item):
found = True
break
if found:
if any(condition(item) for item in a_list):
- all()和any()的参数都是iterable,亦即list或者tuple
- all(iterable):iterable元素都不为False、''、0或者iterable为空,则all(iterable)为True。也就是说,只要iterable元素有一个为"假",则为False,"全‘真’为True,有‘假’为False"。当iterable为空的时候,函数返回值为True。
- any(iterable):iterable的任何元素都为False、0,'',或者iterable全为空,则any(iterable)为False。也就是说所有的iterable都为'假',则any(iterable)为False,"全‘假’为False,有‘真’为True"。当iterable为空的时候,函数返回值为False。
16.属性(property)
class Clock(object):
def __init__(self):
self.__hour = 1
def setHour(self, hour):
if 25 > hour > 0: self.__hour = hour
else: raise Exception("Error Hour!")
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 Exception("Error Hour!")
def __getHour(self):
return self.__hour
hour = property(__getHour, __setHour)
c = Clock();
c.hour = 25
17.使用 with 处理文件打开
f = open("some_file.txt")
try:
data = f.read()
finally:
f.close()
with open("some_file.txt") as f:
data = f.read()
18.使用 with 忽视异常(仅限Python 3)
try:
os.remove("somefile.txt")
except OSError:
pass
from contextlib import ignored
with ignored(OSError):
os.remove("somefile.txt")
19.使用 with 处理加锁
import threading
lock = threading.Lock()
lock.acquire()
try:
finally:
lock.release()
import threading
lock = threading.Lock()
with lock: