4.10Python序列处理函数
本节涉及的序列处理函数为:filter()、zip()、map()、reduce(),但在Python3.3.3+win32 环境下,未执行通过,相关函数未定义。
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:18:40) [MSC v.1600 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.
example4.10.1
>>> a = range(10)
>>> a
range(0, 10)
>>> def f(x):
if x%2 == 0:
return True
>>> f(2)
True
>>> f(3)
>>> filter(f,a)
<filter object at 0x020B1570>
>>> ##应该输出[0,2,4,6,8]
>>> help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| __next__(...)
| x.__next__() <==> next(x)
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
example4.10.2
>>> ##zip()和reduce()
>>> name = ['cui','xiao','hui']
>>> age =[20,21,22]
>>> tel = ['150','186','151']
>>> zip(name,age,tel)
<zip object at 0x020C8CD8>
>>> zip(None,name,age,tel)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
zip(None,name,age,tel)
TypeError: zip argument #1 must support iteration
>>> test = [1,2]
>>> zip(name,age,tel,test)
<zip object at 0x0213B9B8>
>>> map(None,name,age,tel,test)
<map object at 0x02130450>
>>> a = [1,3,5]
>>> b = [2,4,6]
>>>
>>> def mf(x,y)
SyntaxError: invalid syntax
>>> def mf(x,y):
return(x*y)
>>> ##map遍历
>>> map(None,a,b)
<map object at 0x02130490>
>>> map(mf,a,b)
<map object at 0x020C7DD0>
example4.10.3
>>> ##reduce()
>>> i = 0
>>> a =range(1,10)
>>> a
range(1, 10)
>>> n = 0
>>> for i in a:
n+=i
print(n)
>>> foo =[2,18,9,22,17,24,8,12,27]
>>> print filter(lambda x:x%3 == 0,foo)
SyntaxError: invalid syntax
>>> print map(lambda x:x*2 + 10,foo)
SyntaxError: invalid syntax
>>> print reduce(lambda x,y:x+y,foo)
SyntaxError: invalid syntax
>>>