python reduce lambda中reduce和lambda的一个小问题

python官方document中关于lambda的一个小问题_百度知道
python官方document中关于lambda的一个小问题
&&& pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
&&& pairs.sort(key=lambda pair: pair[1])
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
可以解释一下吗,为什么pairs.sort(key=lambda pair:pair[2])会出现语法错...
我有更好的答案
pairs.sort(key=lambda pair:pair[2])表示按每个元素的第三个参数排序;parts的每个元素是只有两个元素元组,因此出现错误
ok,非常感谢,对了,可以问一下,为什么CSDN上发个贴回个问题,怎么没有百度快啊!!你是当然给分的,我这个是其余问题
这个其余的问题我还真不太好回答.可能是这里的各个团队间有竞争的意识吧
采纳率:63%
来自团队:
因为Python列表的下标是从0开始计数的
为您推荐:
其他类似问题
lambda的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。python几个重要的函数(lambda,filter,reduce,map,zip) - 我的MrFiona博客 - 博客园
随笔 - 38, 文章 - 0, 评论 - 0, 引用 - 0
一、匿名函数lambda
lambda argument1,argument2,...argumentN :expression using arguments
1、lambda是一个表达式,而不是一个语句。
因为这一点,lambda可以出现在python语法不允许def出现的地方---例如,在一个列表常量中或者函数调用的参数中,此外,作为一个表达式,lambda返回一个值一个值(一个新的函数),可以选择性地值给一个变量名。相反,def语句总是得在头部将一个新的函数赋值给一个变量名,而不是将这个函数作为结果返回。
2、lambda 的主体是一个单个的表达式,而不是一个代码块。
lambda是一个为编写简单的函数设计的,而def用来处理更大的任务。
&&&f=lambda x,y,z: x+y+z
&&&f(2,3,4)
&&&x=(lambda a=”fee”,b=”fie”,c=”foe”: a+b+c)
&&&x(“wee”)
‘weefiefoe’
通常用lambda来编写跳转表,如下:
&&&L = [lambda x: x**2,
&&lambda x: x**3,
&&lambda x: x**4 ]
&&&for f in L:
print(f(2))
&&&print(L[0](3))
嵌套的lambda,如下:
&&&def action(x):
return (lambda y: x+y)
&&&act=action(99)
&&&action = (lambda x: (lambda y: x+y))
&&&act = action(99)
&&&((lambda x: (lambda y: x+y))(99))(2)
二、map函数
map(function, sequence[, sequence, ...]) -& iterator
通过定义可以看到,这个函数的第一个参数是一个函数,剩下的参数是一个或多个序列,返回值是一个迭代器。
function可以理解为是一个一对一或多对一函数,map的作用是以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的迭代器。
返回可迭代对象,需要list调用来显示所有结果。
&&& list(map(lambda x:x+2, [1, 2, 3]))
&&&list(map(pow,[1,2,3],[2,3,4]))
三、filter函数
filter函数会对指定序列执行过滤操作。
filter函数的定义:
filter(function or None, sequence) -&iterator
filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。
返回可迭代对象,需要list调用来显示所有结果。
&&&list(filter((lambda x: x&0),range(-5,5)))
&&&list(filter(None,range(-5,5)))
[-5, -4, -3, -2, -1, 1, 2, 3, 4]
若function为None,则会返回包含非空元素的迭代器。
四、reduce函数
reduce函数,reduce函数会对参数序列中元素进行累积。
reduce函数的定义:
functools.reduce(function, iterable[, initializer]) &#python3中reduce是在functools模块中
function参数是一个有两个参数的函数,reduce依次从iterable中取一个元素,和上一次调用function的结果做参数再次调用function。
第一次调用function时,如果提供initial参数,会以iterable中的第一个元素和initial作为参数调用function,否则会以iterable中的前两个元素做参数调用function。
def reduce(function, iterable, initializer=None):
it = iter(iterable)
&&&&if initializer is None:
&&&&&&&&value = next(it)
&&&&&&&&value = initializer
&&&&for element in it:
&&&&&&&&value = function(value, element)
return value
&&& functools.reduce(lambda x, y:x+y, [1,2,3,4])
&&& functools.reduce(lambda x, y:x+y, [1,2,3,4], 10)
&&& functools.reduce(lambda x, y:x*y, [1,2,3,4])
如果没有initial参数,这么算:(((1+2)+3)+4)
如果有initial参数,这么算: ((((10+1)+2)+3)+4)
注意:function函数不能为None,function必须是有2个参数的函数。
五、zip函数
其中sorted()和zip()返回一个序列(列表)对象,reversed()、enumerate()返回一个迭代器(类似序列)
定义:zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。
&&& list(zip([1,23,3],[213,45,2])) &#两个列表长度一致
[(1, 213), (23, 45), (3, 2)]
&&& list(zip([1,23,3],[213,45,2,34,54])) &#两个列表长度不一致,以短的为准
[(1, 213), (23, 45), (3, 2)]
zip一些应用:
&&& [ [ i for i in range(3*n+1,3*n+4) ] for n in range(3) ]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
1、二维矩阵变换(矩阵的行列互换)
&&&a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
&&&[ [row[col] for row in a] for col in range(len(a[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
&&&list(zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
&&& map(list,zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
2、*操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple
&&&&x=[1,2,3],y=['a','b','c']
&&&&zip(*zip(x,y))
[(1,2,3),('a','b','c')]
3、使用zip合并相邻的列表项
&&& a = [1, 2, 3, 4, 5, 6]
&&& list(zip(*([iter(a)] * 2)))
[(1, 2), (3, 4), (5, 6)]
&&& group_adjacent = lambda a, k: zip(*([iter(a)] * k))
&&& list(group_adjacent(a, 3))
[(1, 2, 3), (4, 5, 6)]
&&& list(group_adjacent(a, 2))
[(1, 2), (3, 4), (5, 6)]
&&& list(group_adjacent(a, 1))
[(1,), (2,), (3,), (4,), (5,), (6,)]
&&& list(zip(a[::2], a[1::2]))
[(1, 2), (3, 4), (5, 6)]
&&& list(zip(a[::3], a[1::3], a[2::3]))
[(1, 2, 3), (4, 5, 6)]
&&& group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))
&&& list(group_adjacent(a, 3))
[(1, 2, 3), (4, 5, 6)]
&&& list(group_adjacent(a, 2))
[(1, 2), (3, 4), (5, 6)]
&&& list(group_adjacent(a, 1))
[(1,), (2,), (3,), (4,), (5,), (6,)]
4、使用zip和iterators生成滑动窗口 (n -grams)
&&& from itertools import islice
&&& def n_grams(a, n):
z = (islice(a, i, None) for i in range(n))
return zip(*z)
&&& a = [1, 2, 3, 4, 5, 6]
&&& list(n_grams(a, 3))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
&&& list(n_grams(a, 2))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
&&&list(n_grams(a, 4))
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]
5、使用zip反转字典
&&& m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
&&& list(m.items())
[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
&&& list(zip(m.values(), m.keys()))
[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
&&&dict(zip(m.values(), m.keys()))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}Python 特殊语法:filter、map、reduce、lambda
来源:博客园
Python内置了一些特殊函数,这些函数很具python特性。可以让代码更加简洁。 可以看例子: 1 filter(function, sequence) : str = ['a', 'b','c', 'd'] def fun1(s): return s if s != 'a' else None ret = filter(fun1, str) print ret ## ['b', 'c', 'd'] 对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回。 可以看作是过滤函数。 2 map(function, sequence) str = ['a', 'b','c', 'd'] def fun2(s): return s + ".txt" ret = map(fun2, str) print ret ## ['a.txt', 'b.txt', 'c.txt', 'd.txt'] 对sequence中的item依次执行function(item),见执行结果组成一个List返回: map也支持多个sequence,这就要求function也支持相应数量的参数输入: def add(x, y): return x+y print map(add, range(10), range(10)) ##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 3 reduce(function, sequence, starting_value) :def add1(x,y): return x + y print reduce(add1, range(1, 100)) print reduce(add1, range(1, 100), 20) ## 4950 (注:1+2+...+99) ## 4970 (注:1+2+...+99+20) 对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和: 4 lambda : g = lambda s: s + ".fsh" print g("haha") print (lambda x: x * 2) (3) ## haha.fsh ## 6 这是Python支持一种有趣的语法,它允许你快速定义单行的最小函数,类似与C语言中的宏,这些叫做lambda的函数.
免责声明:本站部分内容、图片、文字、视频等来自于互联网,仅供大家学习与交流。相关内容如涉嫌侵犯您的知识产权或其他合法权益,请向本站发送有效通知,我们会及时处理。反馈邮箱&&&&。
学生服务号
在线咨询,奖学金返现,名师点评,等你来互动Python中的map、reduce和filter浅析
转载 & & 作者:
这篇文章主要介绍了Python中的map、reduce和filter,用实例来理解这3个函数,需要的朋友可以参考下
1、先看看什么是 iterable 对象
以内置的max函数为例子,查看其doc: 代码如下:&&& print max.__doc__max(iterable[, key=func]) -& valuemax(a, b, c, ...[, key=func]) -& value
With a single iterable argument, return its largest item.With two or more arguments, return the largest argument.在max函数的第一种形式中,其第一个参数是一个 iterable 对象,既然这样,那么哪些是 iterable 对象呢? 代码如下:&&& max('abcx')&&& 'x'&&& max('1234')&&& '4'&&& max((1,2,3))&&& 3&&& max([1,2,4])&&& 4我们可以使用yield生成一个iterable 对象(也有其他的方式): 代码如下:def my_range(start,end):&&& ''' '''&&& while start &= end:&&&&&&& yield start&&&&&&& start += 1执行下面的代码: 代码如下:for num in my_range(1, 4):&&& print numprint max(my_range(1, 4))将输出: 代码如下:123442、map
在http://docs.python.org/2/library/functions.html#map中如此介绍map函数: 代码如下:map(function, iterable, ...)Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or the result is always a list.map函数使用自定义的function处理iterable中的每一个元素,将所有的处理结果以list的形式返回。例如: 代码如下:def func(x):&&& ''' '''&&& return x*x
print map(func, [1,2,4,8])print map(func, my_range(1, 4))运行结果是: 代码如下:[1, 4, 16, 64][1, 4, 9, 16]也可以通过列表推导来实现: 代码如下:print [x*x for x in [1,2,4,8]]
在http://docs.python.org/2/library/functions.html#reduce中如下介绍reduce函数: 代码如下:reduce(function, iterable[, initializer])Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.这个已经介绍的很明了, 代码如下:reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])相当于计算 代码如下:((((1+2)+3)+4)+5)而: 代码如下:reduce(lambda x, y: x+y, [1, 2, 3, 4, 5],6)相当于计算 代码如下:(((((6+1)+2)+3)+4)+5)
在http://docs.python.org/2/library/functions.html#filter中如下介绍filter函数: 代码如下:filter(function, iterable)Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the resul otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.参数function(是函数)用于处理iterable中的每个元素,如果function处理某元素时候返回true,那么该元素将作为list的成员而返回。比如,过滤掉字符串中的字符a: 代码如下:def func(x):&&& ''' '''&&& return x != 'a'
print filter(func, 'awake')运行结果是: 代码如下:wke这也可以通过列表推导来实现: 代码如下:print ''.join([x for x in 'awake' if x != 'a'])
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具python的reduce累加问题_百度知道
python的reduce累加问题
def pro(num):
a = reduce(sum,num)
print pro([1,2,3])
def pro():
a = reduce(sum,[12,3,4])
print pro()
都是同样的错误提示:
TypeError: 'int' object is not iterable.
该函数的目的就是能做list的...
我有更好的答案
yprint&reduce(lambda&x;y:x&+&nbsp
采纳率:53%
所以是sum的理解有问题reduce(lambda&x,y&:sum([x你可以试试sum(1,2)&,应该报同样的错,y])
为您推荐:
其他类似问题
您可能关注的内容
python的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。

我要回帖

更多关于 reduce lambda 的文章

 

随机推荐