使用reduce()、Python 理解复杂代码 [英] Understanding complex code with reduce(), Python

查看:44
本文介绍了使用reduce()、Python 理解复杂代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下下面例子中reduce()的结构:

Can someone explain the structure of reduce() in the following example:

def f2(list):
        return reduce(lambda string, item: string + chr(item), list, "")

我知道 f2 将 int 列表转换为字符串,但我的问题是理解在这种情况下减少.我知道reduce的基本结构是reduce(function, sequence[, initial]) 但是这个不知何故让我感到困惑.有人可以解释 reduce(lambda string, item: string + chr(item), list, "") 并给我一些类似的例子吗?提前致谢.

I know that f2 converts a list of int's into a string, but my problem is understanding reduce in this context. I know the basic structure of reduce is reduce(function, sequence[, initial]) but this is somehow confusing to me. Can someone explain reduce(lambda string, item: string + chr(item), list, "") and give me some similar examples ? Thanks in advance.

推荐答案

代码将 chr() 应用于列表的每个元素,并将结果连接成单个字符串.

The code applies chr() to every element of the list, and concatenates the results into a single string.

reduce() 调用等效于以下内容:

The reduce() call is equivalent to the following:

return "" + chr(list[0]) + chr(list[1]) + ... + chr(list[list.length - 1])

""reduce() 的第三个参数.

The "" is the third argument to reduce(). The lambda function in

return reduce(lambda string, item: string + chr(item), list, "")

为列表中的每个项目调用.它只是将 chr(item) 附加到前一次迭代的结果中.

is called for every item in the list. It simply appends chr(item) to the result of the previous iteration.

有关使用 reduce() 的更多示例,请参阅 在python中使用reduce()的有用代码

For more examples of using reduce(), see Useful code which uses reduce() in python

这篇关于使用reduce()、Python 理解复杂代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆