python list comprehension在一次迭代中产生两个值 [英] python list comprehension to produce two values in one iteration

查看:73
本文介绍了python list comprehension在一次迭代中产生两个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中生成一个列表,如下所示-

I want to generate a list in python as follows -

[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 .....]

您应该已经知道,除了n, n*n

You would have figured out, it is nothing but n, n*n

我尝试如下在python中编写这样的列表理解-

I tried writing such a list comprehension in python as follows -

lst_gen = [i, i*i for i in range(1, 10)]

但是,这样做会产生语法错误.

But doing this, gives a syntax error.

通过列表理解来生成上述列表的一种好方法是什么?

What would be a good way to generate the above list via list comprehension?

推荐答案

使用 :

>>> from itertools import chain
>>> list(chain.from_iterable((i, i**2) for i in xrange(1, 6)))
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25]

或者您也可以使用发电机函数:

Or you can also use a generator function:

>>> def solve(n):
...     for i in xrange(1,n+1):
...         yield i
...         yield i**2

>>> list(solve(5))
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25]

这篇关于python list comprehension在一次迭代中产生两个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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