python list comprehension to produce two values in one iteration

后端 未结 12 1957
刺人心
刺人心 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 18:04

    The question is old, but just for the curious reader, i propose another possibility: As stated on first post, you can easily make a couple (i, i**2) from a list of numbers. Then you want to flatten this couple. So just add the flatten operation in your comprehension.

    [x for i in range(1, 10) for x in (i,i**2)]
    

提交回复
热议问题