Python 实用技巧

字典中的 get 函数

我们经常需要在字典中初始化数据:

以下是不好的实现方法:

Python代码

  1. navs = {}  
  2. for (portfolio, equity, position) in data:  
  3.     if portfolio not in navs:  
  4.         navs[portfolio] = 0 
  5.     navs[portfolio] += position * prices[equity] 

 

 

使用dict.get(key, default) 删除 if 判断代码:

Python代码

  1. navs = {}  
  2. for (portfolio, equity, position) in data:  
  3.     navs[portfolio] = (navs.get(portfolio, 0)  
  4.                        + position * prices[equity]) 

 

 

这种方式更为直接。

字典中的 setdefault 函数 (1)

当我们要初始化一个可变字典的值。每个字典的值将是一个列表。下面是不好的做法:

初始化可变字典的值:

Python代码

  1. equities = {}  
  2. for (portfolio, equity) in data:  
  3.     if portfolio in equities:  
  4.         equities[portfolio].append(equity)  
  5.     else:  
  6.         equities[portfolio] = [equity] 

 

 

通过 dict.setdefault(key, default) 使这段代码工作的更好:

Python代码

  1. equities = {}  
  2. for (portfolio, equity) in data:  
  3.     equities.setdefault(portfolio, []).append(  
  4.                                          equity) 

 

 

dict.setdefault()等同于“ get, or set & get“ 或"如果没有,就设置"; 如果你的字典Key是复杂的计算或long类型,使用 setdefault 是特别有效的。

字典中的 setdefault 函数 (2)

在我们看到的setdefault字典方法也可以作为一个独立的语句使用:

Python代码

  1. avs = {}  
  2. for (portfolio, equity, position) in data:  
  3.     navs.setdefault(portfolio, 0)  
  4.     navs[portfolio] += position * prices[equity] 

 

 

我们在这里忽略了字典的setdefault方法返回的默认值。我们正利用的setdefault中的作用,仅仅只是在dict中没有 key 的值的时候才会设置。

创建 & 分割字典

如果你有两份 list 对象,希望通过这两个对象构建一个 dict 对象。

Python代码

  1. given = ['John', 'Eric', 'Terry', 'Michael']  
  2. family = ['Cleese', 'Idle', 'Gilliam', 'Palin']  
  3. pythons = dict(zip(given, family))  
  4. >>> pprint.pprint(pythons)  
  5. {'John': 'Cleese',  
  6.  'Michael': 'Palin',  
  7.  'Eric': 'Idle',  
  8.  'Terry': 'Gilliam'} 

 

 

同样,如果希望获取两份列表,也是非常简单:

Python代码

  1. >>> pythons.keys()  
  2. ['John', 'Michael', 'Eric', 'Terry']  
  3. >>> pythons.values()  
  4. ['Cleese', 'Palin', 'Idle', 'Gilliam'] 

 

 

需要注意的是,上面 list 虽然是有序的,但是 dict 中的 keys 和 values 是无序的,这正是因为 dict 本质就是无序存储的。

索引 & 项 (1)

如果你需要一个列表,这里有一个可爱的方式来节省你的输入:

Python代码

  1. >>> items = 'zero one two three'.split()  
  2. >>> print items  
  3. ['zero', 'one', 'two', 'three'] 

 

 

如果我们需要遍历这个 list ,而且需要 index 和 item:

Python代码

  1.                   - or -  
  2. i = 0 
  3. for item in items:      for i in range(len(items)):  
  4.     print i, item               print i, items[i]  
  5.     i += 1 

 

 

索引 & 项 (2): enumerate

通过 enumerate 可以返回 list 中的 (index, item)元组:

Python代码

  1. >>> print list(enumerate(items))  
  2. [(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three')] 

 

 

于是,遍历list获取index 及 item 就更加简单了:

Python代码

  1. for (index, item) in enumerate(items):  
  2.     print index, item 

 

 

Python代码

  1. # compare:              # compare:  
  2. index = 0               for i in range(len(items)):  
  3. for item in items:              print i, items[i]  
  4.     print index, item  
  5.     index += 1 

 

 

不难看出,使用 enumerate 比起下面两种方式,更加简单,更加容易阅读,这正是我们想要的。

下面是例子是如何通过 enumerate 返回迭代器:

Python代码

  1. >>> enumerate(items)  
  2. <enumerate object at 0x011EA1C0>  
  3. >>> e = enumerate(items)  
  4. >>> e.next()  
  5. (0, 'zero')  
  6. >>> e.next()  
  7. (1, 'one')  
  8. >>> e.next()  
  9. (2, 'two')  
  10. >>> e.next()  
  11. (3, 'three')  
  12. >>> e.next()  
  13. Traceback (most recent call last):  
  14.   File "<stdin>", line 1, in ?  
  15. StopIteration 

 

 

默认参数值

这是对于一个初学者常犯的错误,甚至于一些高级开发人员也会遇到,因为他们并不了解 Python 中的 names.

Python代码

  1. def bad_append(new_item, a_list=[]):  
  2.     a_list.append(new_item)  
  3.     return a_list 

 

 

这里的问题是,a_list是一个空列表,默认值是在函数定义时进行初始化。因此,每次调用该函数,你会得到不相同的默认值。尝试了好几次:

Python代码

  1. >>> print bad_append('one')  
  2. ['one']  
  3. >>> print bad_append('two')  
  4. ['one', 'two'] 

 

 

列表是可变对象,你可以改变它们的内容。正确的方式是先获得一个默认的列表(或dict,或sets)并在运行时创建它。

Python代码

  1. def good_append(new_item, a_list=None):  
  2.     if a_list is None:  
  3.         a_list = []  
  4.     a_list.append(new_item)  
  5.     return a_list 

 

 

判断 True 值

Python代码

  1. # do this:        # not this:  
  2. if x:             if x == True:  
  3.     pass              pass 

 

 

它的优势在于效率和优雅。

判断一个list:

Python代码

  1. # do this:        # not this:  
  2. if items:         if len(items) != 0:  
  3.     pass              pass 
  4.  
  5.                   # and definitely not this:  
  6.                   if items != []:  
  7.                       pass 

 

 

True 值

True和False是内置的bool类型的布尔值的实例。谁都只有其中的一个实例。

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

简单比复杂好

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

—Brian W. Kernighan

不要重新发明轮子

在写任何代码之前,

➔ ➔ ➔ ➔

检查python 标准库.http://docs.python.org/library/index.html

检查Python的包索引 (the "Cheese Shop"):

http://cheeseshop.python.org/pypi

Search the web. Google is your friend.

posted @ 2013-07-29 23:20  Excelight  Views(96)  Comments(0)    收藏  举报