4.10Python序列处理函数

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 win32

Type "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
>>> 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值