了解列表理解以在python中展平列表列表 [英] understanding list comprehension for flattening list of lists in python

查看:122
本文介绍了了解列表理解以在python中展平列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这种理解非常适合平展列表列表:

I found this comprehension that works perfectly for flattening a list of lists:

>>> list_of_lists = [(1,2,3),(2,3,4),(3,4,5)]
>>> [item for sublist in list_of_lists for item in sublist]
[1, 2, 3, 2, 3, 4, 3, 4, 5]

与使用itertools.chain()相比,我更喜欢这样做,但我只是听不懂.我尝试用括号括起来的部分,看是否可以降低复杂度,但是现在我更加困惑了:

I like this better than using itertools.chain(), but I just can't understand it. I've tried surrounding parts with parentheses, to see if I could reduce the complexity, but now I'm just more confused:

>>> [(item for sublist in list_of_lists) for item in sublist]
[<generator object <genexpr> at 0x7ff919fdfd20>, <generator object <genexpr> at 0x7ff919fdfd70>, <generator object <genexpr> at 0x7ff919fdfdc0>]

>>> [item for sublist in (list_of_lists for item in sublist)]
[5, 5, 5]

我感到我很难理解,因为我不太了解发电机的工作原理...我的意思是,我以为是,但是现在我很怀疑.就像我说的那样,我喜欢这个习惯用法的紧凑性,这正是我所需要的,但是我讨厌使用我不理解的代码.

I get this feeling that I'm having a hard time understanding because I don't quite understand how generators work... I mean, I thought I did, but now I'm seriously in doubt. Like I said, I love how compact this idiom is, and it's exactly what I need, but I'm loathe to use code that I don't understand.

任何人都可以解释这里到底发生了什么吗?

Can anyone explain what exactly is happening here?

推荐答案

列表理解如下:

[<what i want> <for loops in the order you'd write them naturally>]

在这种情况下,<what I want>是每个sublist中的每个item.要获得这些项目,只需在原始列表中的子列表上循环,然后保存/产生该子列表中的每个项目.因此,列表理解中for循环的顺序与您不使用列表理解时所使用的顺序相同.唯一令人困惑的部分是<what I want>首先出现,而不是在最后一个循环的主体之内.

In this case, <what I want> is every item in every sublist. To get those items, you just loop over the sublists in the original list, and save/yield each item in the sublist. Thus, the order of the for loops in the list comprehension is the same order you would have used if you did not use a list comprehension. The only confusing part is that the <what I want> comes first, and not inside the body of the last loop.

这篇关于了解列表理解以在python中展平列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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