Python 代码改善
2018-02-21 23:06
621 查看
Python reversed list
列表倒序old:
a = [1,2,3,4,5] for i in range(len(a), 0, -1): print i
new:
a = [1,2,3,4,5] for i in reversed(a): print i
Looping over a collection and indices
迭代两个数列,并且得到key ,valueold:
a = [1,2,3,4,5] for i in range(len(a)): print i '->' a[i]
new:
a = [1,2,3,4,5] for key, value in enumerate(a): print key, value
Looping over two collection;
同时循环两个数列old:
a = ['a', 'b', 'c'] colors = ['red', 'blue', 'green', 'yellow', 'white'] length = min(a, colors) for i in range(length): print a[i], '->', colors[i]
new:
a = ['a', 'b', 'c'] colors = ['red', 'blue', 'green', 'yellow', 'white'] for a, color in zip(a, colors): print a, '->', color
Custom sort order
自定义列表排序,比如按照内容长短old:
colors = ['red', 'blue', 'green', 'yellow', 'white'] def compare_length(c1, c2): if len(c1) > len(c2): return 1 if len(c1) < len(c2): return -1 return 0 print sorted(b, cmp=compare_length)
new:
print sorted(b, key=len)
call function until a sentinel value
调用函数直到某一个值old:
while True: with open('package-lock.json', 'r') as f: block = f.read(32) if block == '': break blocks.append(block)
new:
blocks = [] for block in iter(partial(f.read, 32), ''): blocks.append(block)
distinguishing multiple exit point in loop
在循环中有多个退出点(for else)old:
def find(seq, target): found = False for i, value in enumerate(seq): if value == target: found = True break if not found: return -1 return 1
new:
def find(seq, target): for i, value in enumerate(seq): if value == target: found = True break else: return -1 return 1
looping over dictionary key
循环字段键值(python3)old:
d = {'a':'b', 'c':'d'} for k in d.keys(): if k.startswith('r'): del d[k]
new:
d = [k : d[k] for k in d if not k.startswith('c')]
looping over dictionary key and value
循环迭代字典old:
d = {'a':'b', 'c':'d'} for k in d: print k, '->', d[k]
new:
d = {'a':'b', 'c':'d'} for k, value in d.items(): print k, '->', value
construct a dictionary from pairs
构建字典# 两个列表构建字典 names = ['raymond', 'rachel', 'matthew'] colors = ['red', 'green', 'blue'] d = dict(zip(names, colors)) # 单个列表构建字典 d = dict(enumerate(numes))
counting with dictionaries
字典计数old:
colors = ['red', 'green', 'red', 'blue', 'green', 'red'] # ex1 d = {} for color in colors: if color not in d: d[color] = 0 d[color] += 1 # ex2 d = {} for color in colors: d[color] = d.get(color, 0) + 1 # ex3 from collections import defaultdict d = defaultdict(int) for color in colors: d[color] += 1
new:
from collections import Counter colors = ['red', 'green', 'red', 'blue', 'green', 'red'] d = Counter(colors)
grouping with dictionaries
字典分组统计old:
names = ['raymond', 'rachel', 'matthew', 'roger', 'melissa', 'judith'] d = {} for name in names: key = len(name) d.setdefault(key, []).append(name) #In [1]: d #Out[2]: {5: ['roger'], 6: ['rachel', 'judith'], 7: ['raymond', 'matthew', 'melissa']}
new:
from collections import defaultdict names = ['raymond', 'rachel', 'matthew', 'roger', 'melissa', 'judith'] d = defaultdict(list) for name in names: key = len(name) d[key].append(name)
is a dictionary popitem() atomic
字典pop原子操作什么是原子操作:
原子操作就是不会因为进程并发或者线程并发而导致被中断的操作。原子操作的特点就是要么一次全部执行,要么全不执行。不存在执行了一半而被中断的情况。
d = {'judith': 'red', 'matthew': 'red', 'melissa': 'green', 'roger': 'blue'} d.popitem()
Updating multiple state variables
更新多个变量状态old:
def fibonacci(n): x = 0 y = 1 for i in range(n): print x t = y y = x + y x = t
new:
def fibonacci(n): x, y = 0, 1 for i in range(n): yiled x x, y = y, x + y
Concatenating strings
字符串拼接old:
names = ['raymond', 'rachel', 'matthew', 'roger', 'melissa', 'judith'] s = names[0] for name in names[1:]: s += ', ' + name print s
new:
names = ['raymond', 'rachel', 'matthew', 'roger', 'melissa', 'judith'] print ', '.join(names)
Updating sequences
列表更新old:
names = ['raymond', 'rachel', 'matthew', 'roger', 'melissa', 'judith'] # delete del names[0] # pop names.pop(0) # insert names.insert(0, 'eds')
new:
Deques对appendleft()和popleft()具有O(1)速度,list对插入和pop O(n)
Deques have O(1) speed for appendleft() and popleft() while lists have O(n) performance for insert(0, value) and pop(0).
from collections import deque names = ['raymond', 'rachel', 'matthew', 'roger', 'melissa', 'judith'] del names[0] names.popleft() # append names.appendleft('eds')
Using decorators to factor-out administrative logic
使用装饰器来分解管理函数逻辑How to open and close files
使用with 来打开文件new:
with open('./test.yml', 'r') as file: pass
How to use locks
多线程如何使用锁old:
import threading lock = threading.Lock() lock.acquire() try: print 'test1' print 'test2' finally: lock.release()
new:
import threading lock = threading.Lock() with lock: print 'test1' print 'test2'
相关文章推荐
- 编写高质量代码--改善python程序的建议(三)
- 编写高质量代码--改善python程序的建议(六)
- 《编写高质量代码 改善Python程序的91个建议》读后程序学习小结
- 编写高质量代码--改善python程序的建议(一)
- 读《编写高质量代码改善python的91个建议》笔记 建议7:
- 『编写高质量代码——改善 Python 程序的 91 个建议』
- 编写高质量代码--改善python程序的建议(一)
- 编写高质量代码–改善python程序的建议(二)
- 编写高质量代码–改善python程序的建议(三)
- 编写高质量代码--改善python程序的建议(四)
- 编写高质量代码--改善python程序的建议(七)
- 编写高质量代码--改善python程序的建议(四)上
- 编写高质量代码–改善python程序的建议(五)
- [effective python]改善python代码的91个建议-chapter1
- 编写高质量代码--改善python程序的建议(四)下
- [effective python]改善python代码的91个建议-chapter2
- 编写高质量代码–改善python程序的建议(五)
- 编写高质量代码--改善python程序的建议(八)
- 编写高质量代码 改善Python程序的91个建议
- 编写高质量代码--改善python程序的建议(六)续