简体   繁体   中英

Python functools.reduce, how to reduce a list a return a new one

Answering a question I notice that I don't know how to return a list after doing append inside a reduce, for example

import functools

futures = [1,2,3]
records = functools.reduce((lambda res, future: res if (res.append(str(future))  == None) else res), futures, [])

I want the list ['1', '2', '3'] , it is just a minimal example, because I want to do more than map values.

Is there a another way that this horrible if that I put inside the lambda?

You don't have to mutate the result list in your lambda; reduce takes the return value of the function as the result. So your lambda can be as simple as

lambda res, future: res+[str(future)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM