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 返回迭代器:
默认参数值
这是对于一个初学者常犯的错误,甚至于一些高级开发人员也会遇到,因为他们并不了解 Python 中的 names.
问题:
a_list是一个空列表,默认值是在函数定义时进行初始化。因此,每次调用该函数,你会得到不相同的默认值。尝试了好几次:
列表是可变对象,你可以改变它们的内容。正确的方式是先获得一个默认的列表(或dict,或sets)并在运行时创建它。
判断 True 值
它的优势在于效率和优雅。
判断一个list:
True 值
True和False是内置的bool类型的布尔值的实例。谁都只有其中的一个实例。
简单比复杂好
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.