在列表推导中从函数中解包返回值 [英] Unpacking return value from function in List Comprehension

查看:49
本文介绍了在列表推导中从函数中解包返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

def f(v):
    return (v,v+1)

a = [f(i) for i in range(3)]

给予:

[(0, 1), (1, 2), (2, 3)]

我希望更改理解范围,以便提供:

I wish to change the comprehension so that it gives:

[0, 1, 1, 2, 2, 3]

我该怎么做?

推荐答案

或者,您可以使用 itertools.chain.from_iterable :

Or, you can use itertools.chain.from_iterable:

>>> import itertools
>>> list(itertools.chain.from_iterable(f(i) for i in range(3)))
[0, 1, 1, 2, 2, 3]

这篇关于在列表推导中从函数中解包返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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