python中的扁平化列表 [英] Flattening list in python

查看:486
本文介绍了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]
>>>

链接已发布:

在Python中添加浅表

列表的列表(不规则)

如果有人认为这与其他帖子重复,则在理解其工作原理后将其删除.

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:

  1. 一个功能f:
  1. 完全接受2个参数
  2. 返回使用这两个值计算得出的值

  • 可迭代的iter(例如liststr)
  • An iterable 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屋!

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