python list comprehension to produce two values in one iteration

后端 未结 12 1964
刺人心
刺人心 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:41

    A little-known trick: list comprehensions can have multiple for clauses.

    For example:

    >>> [10*x+y for x in range(4) for y in range(3)]
    [0, 1, 2, 10, 11, 12, 20, 21, 22, 30, 31, 32]
    

    In your particular case, you could do:

    >>> [x*x if y else x for x in range(5) for y in range(2)]
    [0, 0, 1, 1, 2, 4, 3, 9, 4, 16]
    

提交回复
热议问题