python扁平化界面,python中的扁平化列表

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]

>>>

Linked already posted :

If anybody thinks this is duplicate to other post, I'll remove it once I understood how it works.

Thanks.

解决方案

What reduce does, in plain English, is that it takes two things:

A function f that:

Accepts exactly 2 arguments

Returns a value computed using those two values

An iterable iter (e.g. a list or str)

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.

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])

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].

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值