You can use list-comprehensions for both tasks (creating b
and c
lists)
a = [10, 20, 30, 40, 50, 60]
b = [i+j for i, j in zip(a[::2], a[1::2])]
print(b) # [30, 70, 110]
c = [x / b[i//2] for i, x in enumerate(a)]
print(c) # [0.3333333333333333, 0.6666666666666666, 0.42857142857142855, 0.5714285714285714, 0.45454545454545453, 0.5454545454545454]
If you really want fractions, you can use the fractions
module and its Fraction
data type:
from fractions import Fraction
# same code as before
c = [Fraction(x, b[i//2]) for i, x in enumerate(a)]
print(c) # [Fraction(1, 3), Fraction(2, 3), Fraction(3, 7), Fraction(4, 7), Fraction(5, 11), Fraction(6, 11)]
Note
As @LaurentH. notices in the comments, the above works only for chunks (you call them windows) of size 2. For a more general approach, you can define a generator that would yield
them for you:
# taken from https://stackoverflow.com/a/312464/6162307
def yield_chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
b = [sum(chunk) for chunk in yield_chunks(a, 2)]
# same code
Example for n = 3
:
n = 3
b = [sum(chunk) for chunk in yield_chunks(a, n)]
print(b) # [60, 150]
c = [x / b[i//n] for i, x in enumerate(a)]
print(c) # [0.16666666666666666, 0.3333333333333333, 0.5, 0.26666666666666666, 0.3333333333333333, 0.4]