python list comprehension to produce two values in one iteration

后端 未结 12 1960
刺人心
刺人心 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条回答
  •  -上瘾入骨i
    2021-02-03 17:55

    List comprehensions generate one element at a time. Your options are, instead, to change your loop to only generate one value at a time:

    [(i//2)**2 if i % 2 else i//2 for i in range(2, 20)]
    

    or to produce tuples then flatten the list using itertools.chain.from_iterable():

    from itertools import chain
    
    list(chain.from_iterable((i, i*i) for i in range(1, 10)))
    

    Output:

    >>> [(i//2)**2 if i % 2 else i//2 for i in range(2, 20)]
    [1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]
    >>> list(chain.from_iterable((i, i*i) for i in range(1, 10)))
    [1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]
    

提交回复
热议问题