python中的扁平化列表 [英] Flattening list in python
问题描述
我看过很多关于如何在Python中扁平化列表的帖子.但是我永远无法理解它是如何工作的:reduce(lambda x,y:x+y,*myList)
I have seen many posts regarding how to flatten a list in Python. But I was never able to understand how this is working: reduce(lambda x,y:x+y,*myList)
有人可以解释一下它是如何工作的:
Could someone please explain, how this is working:
>>> myList = [[[1,2,3],[4,5],[6,7,8,9]]]
>>> reduce(lambda x,y:x+y,*myList)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
链接已发布:
如果有人认为这与其他帖子重复,则在理解其工作原理后将其删除.
If anybody thinks this is duplicate to other post, I'll remove it once I understood how it works.
谢谢.
推荐答案
用简单的英语来说,reduce
的作用是需要做两件事:
What reduce
does, in plain English, is that it takes two things:
- 一个功能
f
:
- 完全接受2个参数
- 返回使用这两个值计算得出的值
iter
(例如list
或str
)
iter
(e.g. a list
or str
) reduce
计算f(iter[0],iter[1])
的结果(可迭代的前两项),并跟踪刚刚计算出的该值(称为temp
). reduce
然后计算f(temp,iter[2])
,现在跟踪该新值.此过程一直持续到iter
中的每个项目都已传递到f
中,并返回计算出的最终值.
reduce
computes the result of f(iter[0],iter[1])
(the first two items of the iterable), and keeps track of this value that was just computed (call it temp
). reduce
then computes f(temp,iter[2])
and now keeps track of this new value. This process continues until every item in iter
has been passed into f
, and returns the final value computed.
在将*myList
传递给reduce
函数时使用*
的方法是,它需要一个可迭代的并将其转换为多个参数.这两行做相同的事情:
The use of *
in passing *myList
into the reduce
function is that it takes an iterable and turns it into multiple arguments. These two lines do the same thing:
myFunc(10,12)
myFunc(*[10,12])
对于myList
,您使用的list
仅包含一个list
.因此,将*
放在前面将myList
替换为myList[0]
.
In the case of myList
, you're using a list
that contains only exactly one list
in it. For that reason, putting the *
in front replaces myList
with myList[0]
.
关于兼容性,请注意reduce
函数在Python 2中完全可以正常工作,但是在Python 3中,您必须这样做:
Regarding compatibility, note that the reduce
function works totally fine in Python 2, but in Python 3 you'll have to do this:
import functools
functools.reduce(some_iterable)
这篇关于python中的扁平化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!