Search code examples
pythonlistlist-comprehensionmultiplication

python multiply list elements in a changing manner


I want to decay elements of a list such that on every 5 element, the elements will be reduced by half. For example, a list of ones with length 10 will become:

[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

[1,1,1,1,1,0.5,0.5,0.5,0.5,0.5,0.25,0.25,0.25,0.25,0.25]

I tried list comprehensions and a basic for loop, but I couldn't construc the logic behind it.


Solution

  • Is this what you're looking for?

    >>> x = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    >>> r = [v*2**(-(i//5)) for i, v in enumerate(x)]
    >>> r
    [1, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 0.25]
    >>>