列表理解的结果是平面列表 [英] flat list as a result of list comprehension

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

问题描述

我使用列表理解的方式是,对于每个元素,我有2个结果值:

I use list comprehension in such a way that for each element I have 2 resulting values:

my_list = [10,20,30]
res_list = [ (x*2, x*3) for x in my_list ]
res_list # [(20, 30), (40, 60), (60, 90)]

但是我需要一个扁平化的列表,所以我必须执行另一种理解:

But I need to have a flatten list, so I have to perform another comprehension:

res_list_1 = [yy for xx in res_list for yy in xx]
res_list_1 # [20, 30, 40, 60, 60, 90]

有什么方法可以避免这种情况,并在第一次理解时直接获得平坦的res_list?

Is there any way to avoid this and get flat res_list directly on the first comprehension?

推荐答案

tuple放在末尾:

res_list_1 = [item for object in my_list for item in (object*2, object*3)]

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

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