Understanding complex code with reduce(), Python

好久不见. 提交于 2019-12-11 20:11:06

问题


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

def f2(list):
        return 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.


回答1:


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

The reduce() call is equivalent to the following:

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

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

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

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

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




回答2:


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

roughly translates to

string = ""
for item in list:
    string = string + chr(item)
return string



回答3:


Reduce does something usually called a fold. E.g., if you have a list ls = [a,b,c,d] and a binary operation def plus(x,y): x + y, then reduce(plus, ls) gets folded to

plus(plus(plus(a, b), c), d)

which equals

(((a+b)+c)+d)

Your f2 is doing something similar, namely appending strings (after converting them from integers): (I really hope those parens match...)

(((("" + chr(a)) + chr(b)) + chr(c)) + chr(d))

with a supplied initial value of "" (which is needed when a folding operation has two different input types)

@ python experts: I'm not sure if reduce is a left fold, it seemed more naturally to me. Please tell me if I'm wrong.



来源:https://stackoverflow.com/questions/10429079/understanding-complex-code-with-reduce-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!