Home > Enterprise >  Add a sequence of n numbers, getting n from another list, in Python
Add a sequence of n numbers, getting n from another list, in Python

Time:09-30

I have the following two lists:

numlist = [1, 1, 1, 1, 4, 1, 1, 4, 1, 2]
lenwords = [2,3,5]

I want to see the number at each index in len words as such:

for number in range(len(lenwords)):
    print(lenwords[number])

And then take that number of items in numlist suggested by each index in lenwords (2,3,5) and add them together, like so:

add 1 1 then 1 1 4 then 1 1 4 1 2

I'm thinking that I could use itertools, but not sure how to do so.

CodePudding user response:

I make an iterable out of numlist, then iterate over lenwords, using itertools.islice to pull out the count you want from the numlist generator.

https://docs.python.org/3/library/itertools.html#itertools.islice

import itertools

def sumlengths(numlist, lenwords):
    numbers = iter(numlist)
    for length in lenwords:
        yield sum(itertools.islice(numbers, length))

numlist = [1, 1, 1, 1, 4, 1, 1, 4, 1, 2]
lenwords = [2,3,5]
print (*sumlengths(numlist, lenwords))

2 6 9

I did not validate the length of the inputs.

CodePudding user response:

with out using ittertools:

numlist = [1, 1, 1, 1, 4, 1, 1, 4, 1, 2]
lenwords = [2, 3, 5]
counter = 0
for number in lenwords:
    q = numlist[counter:counter number]
    print(sum(q))
    counter  = number

output

2
6
9

CodePudding user response:

Another approach:

numlist = [1, 1, 1, 1, 4, 1, 1, 4, 1, 2]
lenwords = [2,3,5]
gen = iter(numlist)
result = []

for n in lenwords:
    total = 0
    for _ in range(n):
        total  = next(gen)
    result.append(total)

The resulting list total is [2, 6, 9], as desired.

  • Related