Python实用技巧 Pythoner必由之路

发布时间:2020-05-26编辑:脚本学堂
本文详细介绍了python编程中的一些技巧,网上有朋友说这篇文章是pythoner们的必经之路,呵呵,如果你也这么努力与向往成为python大牛,这篇文章不要错过。
于是,遍历list获取index 及 item 就更加简单了:
 

复制代码 代码示例:

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 比起下面两种方式,更加简单,更加容易阅读,这正是我们想要的。

例子,通过 enumerate 返回迭代器:
 

复制代码 代码示例:
>>> 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 

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

复制代码 代码示例:
def bad_append(new_item, a_list=[]): 
    a_list.append(new_item) 
    return a_list 

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

复制代码 代码示例:
>>> print bad_append('one') 
['one'] 
>>> print bad_append('two') 
['one', 'two'] 

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

复制代码 代码示例:
def good_append(new_item, a_list=None): 
    if a_list is None: 
        a_list = [] 
    a_list.append(new_item) 
    return a_list 

判断 True 值
 

复制代码 代码示例:
# do this:        # not this: 
if x:             if x == True: 
    pass              pass 

它的优势在于效率和优雅。
判断一个list:
 

复制代码 代码示例:
# do this:        # not this: 
if items:         if len(items) != 0: 
    pass              pass 
 
                  # and definitely not this: 
                  if items != []: 
                      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 标准库.
检查Python的包索引 (the "Cheese Shop"):
http://cheeseshop.python.org/pypi
Search the web. Google is your friend.