python list comprehension to produce two values in one iteration

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

    >>> lst_gen = [[i, i*i] for i in range(1, 10)]
    >>> 
    >>> lst_gen
    [[1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
    >>> 
    >>> [num for elem in lst_gen for num in elem]
    [1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]
    

    Here is my reference http://docs.python.org/2/tutorial/datastructures.html

提交回复
热议问题