首先是sum函数.
最常见的用法似乎是:
>>> sum([1,2,3])
6
但其实这是默认首个元素是数字0.我们可以指定其他数字:
>>> sum([1,2,3],100)
106
也可指定一个列表对象:
>>> sum([[1],[2],[3]],[])
[1, 2, 3] >>> sum([[1],[2],[3]],['head'])
['head', 1, 2, 3]
来看filter,None参数特别用法:
>>> filter(None,(1,2,None,3))
(1, 2, 3)
>>> filter(lambda x:x,(1,2,None,3))
(1, 2, 3)
map也有类似设置:
>>> map(None,range(3),range(3))
[(0, 0), (1, 1), (2, 2)]
>>> map(lambda x,y:(x,y),range(3),range(3))
[(0, 0), (1, 1), (2, 2)]
字符串也能使用+运算符啊.不过当你想用sum来合并字符时,会被贴心地提示:
>>> sum(['a','b','c'],'') Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
sum(['a','b','c'],'')
TypeError: sum() can't sum strings [use ''.join(seq) instead]