python list comprehension to produce two values in one iteration

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

    Another option:

    reduce(lambda x,y: x + [y, y*y], range(1,10), [])
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2021-02-03 17:44

    Lots of tricks in this thread. Here is another using a one liner generator without imports

    x = (lamdba : [[(yield i), (yield i**2)] for i in range(10)])()
    

    EDIT: This will raise DeprecatedWarning in Python 3.7 and SyntaxError in Python 3.8: https://docs.python.org/dev/whatsnew/3.7.html#deprecated-python-behavior

    0 讨论(0)
  • 2021-02-03 17:51

    Another option, might seem perverse to some

    >>> from itertools import izip, tee
    >>> g = xrange(1, 11)
    >>> x, y = tee(g)
    >>> y = (i**2 for i in y)
    >>> z = izip(x, y)
    >>> output = []
    >>> for k in z:
    ...     output.extend(k)
    ... 
    >>> print output
    [1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81, 10, 100]
    
    0 讨论(0)
  • 2021-02-03 17:53

    Use itertools.chain.from_iterable:

    >>> from itertools import chain
    >>> list(chain.from_iterable((i, i**2) for i in xrange(1, 6)))
    [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]
    

    Or you can also use a generator function:

    >>> def solve(n):
    ...     for i in xrange(1,n+1):
    ...         yield i
    ...         yield i**2
    
    >>> list(solve(5))
    [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]
    
    0 讨论(0)
提交回复
热议问题