Idiomatic Python, well format in python

来源:互联网 发布:淘宝怎么异地发货 编辑:程序博客网 时间:2024/05/18 01:27

Looping over a range of numbers
exercise 1:
for i in [0, 1, 2, 3, 4, 5]:
print i**2
for i in range(6):
print i**2
Idiomatic python
for i in xrange(6):
print i**2
xrange creates an iterator over the range producing the values one at a time. This approach is much more memory efficient than range. xrange was renamed to range in python 3.
exercise 2:
遍历列表
colors = [‘red’, ‘green’, ‘blue’, ‘yellow’]

for i in range(len(colors)):
print colors[i]
建议写法:
for color in colors:
print color
反向遍历
colors = [‘red’, ‘green’, ‘blue’, ‘yellow’]
for i in range(len(colors)-1, -1, -1):
print colors[i]
建议写法:
for color in reversed(colors):
print color

循环遍历集合以及其索引
colors = [‘red’, ‘green’, ‘blue’, ‘yellow’]
for i in range(len(colors)):
print i, ‘—>’, colors[i]
建议写法:
for i, color in enumerate(colors):
print i, ‘—>’, color
It’s fast and beautiful and saves you from tracking the individual indices and incrementing them.
Whenever you find yourself manipulating indices [in a collection], you’re probably doing it wrong.

遍历两个集合
names = [‘raymond’, ‘rachel’, ‘matthew’]
colors = [‘red’, ‘green’, ‘blue’, ‘yellow’]
n = min(len(names), len(colors))
for i in range(n):
print names[i], ‘—>’, colors[i]

for name, color in zip(names, colors):
print name, ‘—>’, color
建议写法:
for name, color in izip(names, colors):
print name, ‘—>’, color

zip creates a new list in memory and takes more memory. izip is more efficient than zip. Note: in python 3 izip was renamed to zip and promoted to a builtin replacing the old zip.

排序遍历
colors = [‘red’, ‘green’, ‘blue’, ‘yellow’]

Forward sorted order
for color in sorted(colors):
print colors
Backwards sorted order
for color in sorted(colors, reverse=True):
print colors
自定义排序遍历
colors = [‘red’, ‘green’, ‘blue’, ‘yellow’]
def compare_length(c1, c2):
if len(c1) < len(c2): return -1
if len(c1) > len(c2): return 1
return 0
print sorted(colors, cmp=compare_length)
建议写法
print sorted(colors, key=len)
The original is slow and unpleasant to write. Also, comparison functions are no longer available in python 3.

Call a function until a sentinel value

blocks = []
while True:
block = f.read(32)
if block == ”:
break
blocks.append(block)

Better

blocks = []
for block in iter(partial(f.read, 32), ”):
blocks.append(block)
iter takes two arguments. The first you call over and over again and the second is a sentinel value.
遍历字典的键值
d = {‘matthew’: ‘blue’, ‘rachel’: ‘green’, ‘raymond’: ‘red’}
for k in d:
print k
for k in d.keys():
if k.startswith(‘r’):
del d[k]
遍历字典的键值对
Not very fast, has to re-hash every key and do a lookup
for k in d:
print k, ‘—>’, d[k]

Makes a big huge list
for k, v in d.items():
print k, ‘—>’, v

Better

for k, v in d.iteritems():
print k, ‘—>’, v

iteritems() is better as it returns an iterator. Note: in python 3 there is no iteritems() and items() behaviour is close to what iteritems() had. See documentation.

从两个列表中构造一个字典
names = [‘raymond’, ‘rachel’, ‘matthew’]
colors = [‘red’, ‘green’, ‘blue’]

d = dict(izip(names, colors))
result: {‘matthew’: ‘blue’, ‘rachel’: ‘green’, ‘raymond’: ‘red’} For python 3: d = dict(zip(names, colors))

将列表转化为字典{color:count}

colors = [‘red’, ‘green’, ‘red’, ‘blue’, ‘green’, ‘red’]

comment: Simple, basic way to count. A good start for beginners.
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1

result : {‘blue’: 1, ‘green’: 2, ‘red’: 3}

Grouping with dictionaries – Part I and II

names = [‘raymond’, ‘rachel’, ‘matthew’, ‘roger’,
‘betty’, ‘melissa’, ‘judith’, ‘charlie’]

In this example, we’re grouping by name length
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)

结果: {5: [‘roger’, ‘betty’], 6: [‘rachel’, ‘judith’], 7: [‘raymond’, ‘matthew’, ‘melissa’, ‘charlie’]}

d = {}
for name in names:
key = len(name)
d.setdefault(key, []).append(name)
建议写法:
d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)

unpacking 序列

p = ‘Raymond’, ‘Hettinger’, 0x30, ‘python@example.com’

comments: A common approach / habit from other languages
fname = p[0]
lname = p[1]
age = p[2]
email = p[3]
Better
fname, lname, age, email = p

fibonacci函数
def fibonacci(n):
x = 0
y = 1
for i in range(n):
print x
t = y
y = x + y
x = t
well done:
def fibonacci(n):
x, y = 0, 1
for i in range(n):
print x
x, y = y, x + y
链接字符串:
names = [‘raymond’, ‘rachel’, ‘matthew’, ‘roger’,
‘betty’, ‘melissa’, ‘judith’, ‘charlie’]

s = names[0]
for name in names[1:]:
s += ‘, ’ + name
print s
建议写法:
print ‘, ‘.join(names)

更新队列
names = [‘raymond’, ‘rachel’, ‘matthew’, ‘roger’,
‘betty’, ‘melissa’, ‘judith’, ‘charlie’]

del names[0]

The below are signs you’re using the wrong data structure
names.pop(0)
print names
names.insert(0, ‘mark’)
print names
建议写法: deque是collections包里面的对象,高性能双端队列
from collections import deque
names = deque([‘raymond’, ‘rachel’, ‘matthew’, ‘roger’,
‘betty’, ‘melissa’, ‘judith’, ‘charlie’])

More efficient with deque
del names[0]
names.popleft()
print names
names.appendleft(‘mark’)
print names

Using decorators to factor-out administrative logic
Mixes business / administrative logic and is not reusable
def web_lookup(url, saved={}): if url in saved:
return saved[url]
page = urllib.urlopen(url).read()
saved[url] = page
return page
建议写法
@cache
def web_lookup(url):
return urllib.urlopen(url).read()

如何打开和关闭文件
f = open(‘data.txt’)
try:
data = f.read()
finally:
f.close()
建议写法
with open(‘data.txt’) as f:
data = f.read()
如何使用锁 制作锁
lock = threading.Lock()

方式一
lock.acquire()
try:
print ‘Critical section 1’
print ‘Critical section 2’
finally:
lock.release()

建议方式
with lock:
print ‘Critical section 1’
print ‘Critical section 2’
忽略暂存文件因素
try:
os.remove(‘somefile.tmp’)
except OSError:
pass
建议方式
with ignored(OSError):
os.remove(‘somefile.tmp’)

result = []
for i in range(10):
s = i ** 2
result.append(s)
print sum(result)

建议方式:
print sum(i**2 for i in xrange(10))

还有函数lamdba,filter map, reduce,zip,range,sum,等函数的使用。暂时不列出

0 0
原创粉丝点击