[英]Flattening list in python
我看过很多关于如何在Python中展平列表的帖子。 但我无法理解这是如何工作的: reduce(lambda x,y:x+y,*myList)
有人可以解释,这是如何工作的:
>>> 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]
>>>
链接已发布:
如何在不使用任何for或while循环的情况下将列表列表打印到python中的单个列表中?
如果有人认为这与其他帖子重复,我会在理解它的工作原理后删除它。
谢谢。
简单来说, reduce
是它需要两件事:
f
:
iter
(例如list
或str
) reduce
计算f(iter[0],iter[1])
的结果f(iter[0],iter[1])
(可迭代的前两项),并跟踪刚刚计算的这个值(称之为temp
)。 reduce
然后计算f(temp,iter[2])
,现在跟踪这个新值。 这个过程一直持续到iter
每个项都被传递给f
,并返回计算出的最终值。
将*myList
传递给reduce
函数时使用*
是它需要一个可迭代的并将其转换为多个参数。 这两行做同样的事情:
myFunc(10,12)
myFunc(*[10,12])
对于myList
,您使用的list
中只包含一个list
。 因此,将*
放在前面myList
myList[0]
替换为myList[0]
。
关于兼容性,请注意reduce
函数在Python 2中完全正常,但在Python 3中你必须这样做:
import functools
functools.reduce(some_iterable)
它相当于:
def my_reduce(func, seq, default=None):
it = iter(seq)
# assign either the first item from the iterable to x or the default value
# passed to my_reduce
x = next(it) if default is None else default
#For each item in iterable, update x by appying the function on x and y
for y in it:
x = func(x, y)
return x
...
>>> my_reduce(lambda a, b: a+b, *myList, default=[])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> my_reduce(lambda a, b: a+b, *myList)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> from operator import add
>>> my_reduce(add, *myList)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> my_reduce(lambda a, b: a+b, ['a', 'b', 'c', 'd'])
'abcd'
文档字符串的reduce
有很好的解释:
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
首先,这是一个非常糟糕的方法。 你知道吗
reduce(f, [a, b, c, d])
运行
f(f(f(f(a, b), c), d)
由于f
是lambda x,y:x+y
,这相当于
((a + b) + c) + d
对于列表, a + b
是列表的串联,因此这将连接每个列表。
这很慢,因为每个步骤都必须从头开始创建一个新列表。
首先,我不知道为什么它被包裹在一个数组然后splatted( *
)。 这将以相同的方式工作:
>>> 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]
说明: reduce
接受一个带有两个参数的方法 - 累加器和元素。 它使用每个元素调用方法,然后将累加器设置为lambda的结果。 因此,您基本上将所有内部列表连接在一起。
这是一步一步的解释:
myList[0]
,即[1,2,3]
[1,2,3]
和[4,5]
调用lambda,它返回[1,2,3,4,5]
,它被赋值给累加器 [1,2,3,4,5]
和[6,7,8,9]
调用lambda,它返回[1,2,3,4,5,6,7,8,9]
reduce
返回
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.