简体   繁体   English

在 Python 中添加 n 个数字的序列,从另一个列表中获取 n

[英]Add a sequence of n numbers, getting n from another list, in Python

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:我想以 len 字的形式查看每个索引处的数字:

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:然后将 lenwords (2,3,5) 中每个索引建议的 numlist 中的项目数加在一起,如下所示:

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.我在想我可以使用 itertools,但不确定如何使用。

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.我从 numlist 中创建一个可迭代对象,然后迭代 lenwords,使用 itertools.islice 从 numlist 生成器中提取您想要的计数。

https://docs.python.org/3/library/itertools.html#itertools.islice 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 2 6 9

I did not validate the length of the inputs.我没有验证输入的长度。

with out using ittertools:不使用 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 output

2
6
9

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.根据需要,结果列表total[2, 6, 9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM