简体   繁体   English

在Python中获取索引滑动窗口的总和

[英]Taking the sum of a sliding window of indices in python

I have looked around but have been unable to find out why my code is failing, and how to do it right. 我环顾四周,但无法找出我的代码为什么失败以及如何正确执行。 I'm new (3 days) to coding, so forgive my noobishness. 我是编码新手(三天),所以请原谅我的笨拙。

I start with a list of integers, and essentially I want to make a new or updated list where the new list's first index has a value = the sum of the first 10 values of the original list (0-10), and then the new list's second index has a value = the sum of the original list's (1-11) index values. 我从整数列表开始,从本质上讲,我想创建一个新列表或更新列表,其中新列表的第一个索引的值=原始列表的前10个值的总和(0-10),然后是新列表列表的第二个索引的值=原始列表的(1-11)索引值的总和。

The problem is that it adds everything incorrectly, and in a manner such that I have not yet been able to figure out the pattern. 问题在于它错误地添加了所有内容,并且以某种方式使我还无法弄清楚模式。

Here's what I have: 这是我所拥有的:

def sum_range(filename, grouping = 10):
    """sums up the ss values for 'groupings' numbers of indices.
    Shows ALL results, regardless of how high or low strandedness is"""

    sslist = ssc_only(filename)
    # "ssc_only(filename)" takes my input and returns it as a list of int,
    # which I want to use for this function

    sslist = [sum(sslist[i:i+grouping]) for i in sslist]

    return sslist

I think you probably want for i in range(len(sslist)) (use xrange instead of range in python 2 if you're concerned about memory consumption). 我认为您可能想要for i in range(len(sslist))使用for i in range(len(sslist))如果您担心内存消耗,请使用xrange代替python 2中的range )。

lstlen=len(sslist)
sslist = [sum(sslist[i:min(i+grouping,lstlen)]) for i in range(lstlen)]

You are looping over list items instead of over list indices 您正在遍历列表项,而不是遍历列表索引

Of course, your last 10 elements will be the sum of less than 10 elements. 当然,您的最后10个元素将是少于10个元素的总和。 As I don't know what you want to do with those elements, I'll leave it to you to figure out what you want to do with them. 因为我不知道您想对这些元素做什么,所以我将留给您了解您想对它们做些什么。

Don't think your summing is right ... also if you're making groups of 10, you'll get 10 less samples than in the original list - this give len(r) - 10 in the expression below. 不要以为您的求和是正确的...同样,如果您要组成10个一组,则样本数将比原始列表少10个-这在下面的表达式中给出len(r) - 10

>>> r = range(20)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [sum(r[n:10+n]) for n in range(len(r)-10)]
[45, 55, 65, 75, 85, 95, 105, 115, 125, 135]

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

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