Python实用技巧-成为Pythoner必经之路
- shuangxi - ITeye论坛最新讨论 本文主要记录 Python 中一些常用技巧,本文重点描述的是告诉你怎么写才是更好. 如果你并不熟悉Python语法,希望你能在下面代码片段中看到Python的简单、优雅; 如果你象我这样,对 Python 有兴趣或并正在学习,我相信下面的技巧并不会让你失望; 如果你已经是一名 Pythoner ,那么很乐于你分享你的经验和技巧.
def make_squares(key, value=0): """Return a dictionary and a list...""" d = {key: value} l = [key, value] return d, l
def __init__(self, first, second, third, fourth, fifth, sixth): output = (first + second + third + fourth + fifth + sixth)
VeryLong.left_hand_side \ = even_longer.right_hand_side()另外,使用反斜杠是有风险的,如果你添加一个空格在反斜杠后面,它就出错了。此外,它使代码难看。
>>> print 'o' 'n' "e" one
>>> print 't' r'\/\/' """o""" t\/\/o
>>> a = 'three' >>> b = 'four' >>> a b File "<stdin>", line 1 a b ^ SyntaxError: invalid syntax
if foo == 'blah': do_something() do_one() do_two() do_three()
if foo == 'blah': do_something() do_one(); do_two(); do_three()
# !!! BUG: ... # !!! FIX: This is a hack # ??? Why is this here?注释对于任何语言开发者来说已经最基本的东西了,这里就不详细说了.
temp = a a = b b = temp
b, a = a, b
>>> info =['David', 'Pythonista', '+1250'] >>> name, title, phone = info >>> name 'Davids' >>> title 'Pythonista' >>> phone '+1250'
>>> people = [info, ['Guido', 'BDFL', 'unlisted']] >>> for (name, title, phone) in people: ... print name, phone ... David +1250 Guido unlisted
>>> david, (gname, gtitle, gphone) = people >>> gname 'Guido' >>> gtitle 'BDFL' >>> gphone 'unlisted' >>> david ['David', 'Pythonista', '+1250']
>>> 1, (1,)
>>> (1,) (1,)
>>> (1) 1
>>> () () >>> tuple() ()
>>> value = 1, >>> value # is a tuple, not a int (1,)
>>> 1 + 1 2 >>> _ 2
>>> import math >>> math.pi / 3 1.0471975511965976 >>> angle = _ >>> math.cos(angle) 0.50000000000000011 >>> _ 0.50000000000000011
colors = ['red', 'blue', 'green', 'yellow']当我们需要将上面的列表连接成一个字符串。尤其当 list 是一个很大的列表时....
result = '' for s in colors: result += s这种方式效率非常低下的,它有可怕的内存使用问题,至于为什么,如果你是 javaer 的话,其中的 string 连接,我想你并不陌生。
result = ''.join(colors)
result = ''.join(fn(i) for i in items)
for key in d: print key
for key in d.keys(): print key
# do this: if key in d: ...do something with d[key] # not this: if d.has_key(key): ...do something with d[key]
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])这种方式更为直接。
equities = {} for (portfolio, equity) in data: if portfolio in equities: equities[portfolio].append(equity) else: equities[portfolio] = [equity]
equities = {} for (portfolio, equity) in data: equities.setdefault(portfolio, []).append( equity)
avs = {} for (portfolio, equity, position) in data: navs.setdefault(portfolio, 0) navs[portfolio] += position * prices[equity]
given = ['John', 'Eric', 'Terry', 'Michael'] family = ['Cleese', 'Idle', 'Gilliam', 'Palin'] pythons = dict(zip(given, family)) >>> pprint.pprint(pythons) {'John': 'Cleese', 'Michael': 'Palin', 'Eric': 'Idle', 'Terry': 'Gilliam'}
>>> pythons.keys() ['John', 'Michael', 'Eric', 'Terry'] >>> pythons.values() ['Cleese', 'Palin', 'Idle', 'Gilliam']
>>> items = 'zero one two three'.split() >>> print items ['zero', 'one', 'two', 'three']
- or - i = 0 for item in items: for i in range(len(items)): print i, item print i, items[i] i += 1
>>> print list(enumerate(items)) [(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three')]
for (index, item) in enumerate(items): print index, item
# compare: # compare: index = 0 for i in range(len(items)): for item in items: print i, items[i] print index, item index += 1
>>> enumerate(items) <enumerate object at 0x011EA1C0> >>> e = enumerate(items) >>> e.next() (0, 'zero') >>> e.next() (1, 'one') >>> e.next() (2, 'two') >>> e.next() (3, 'three') >>> e.next() Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration
def bad_append(new_item, a_list=[]): a_list.append(new_item) return a_list
>>> print bad_append('one') ['one'] >>> print bad_append('two') ['one', 'two']
def good_append(new_item, a_list=None): if a_list is None: a_list = [] a_list.append(new_item) return a_list
# do this: # not this: if x: if x == True: pass pass
# do this: # not this: if items: if len(items) != 0: pass pass # and definitely not this: if items != []: pass
False | True |
False (== 0) | True (== 1) |
"" (empty string) | any string but "" (" ", "anything") |
0, 0.0 | any number but 0 (1, 0.1, -1, 3.14) |
[], (), {}, set() | any non-empty container ([0], (None,), ['']) |
None | almost any object that's not explicitly False |