python list comprehension to produce two values in one iteration

后端 未结 12 1959
刺人心
刺人心 2021-02-03 17:20

I want to generate a list in python as follows -

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

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

12条回答
  •  醉话见心
    2021-02-03 17:53

    Use itertools.chain.from_iterable:

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

提交回复
热议问题