python list comprehension to produce two values in one iteration

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

    Try this two liner

    lst = [[i, i*i] for i in range(10)]
    [lst.extend(i) for i in lst]
    

    Change math as necessary.

    EVEN BETTER

    #Change my_range to be the number you want range() function of
    start = 1
    my_range = 10
    lst = [i/2 if i % 2 == 0 else ((i-1)/2)**2 for i in range(start *2, my_range*2 - 1)]
    

提交回复
热议问题