【问题标题】:function to find the cumulative sum of every 5 elements.in python在python中查找每5个元素的累积和的函数
【发布时间】:2021-04-03 18:51:16
【问题描述】:

可能有一些元素可能不是 int 类型,函数需要优雅地处理异常并传递给下一个元素。函数应该返回一个列表,其中每个元素都应该是输入列表中每 5 个元素的累积和。

sample_input = [50, 30, 20, 0, "catch_me", 0, "you_got_me", "did_you_really_catch", 40, 50, "20", 0, 0, 0, 10]
expected_output = [100, 190, 200]

到目前为止,我已经尝试过以下代码片段

a=[]
count=0
n=5
for i in sample_input:

    if isinstance(i,int):
        for j in range(len(sample_input)/5):
            count+=i
            a.append(count)
print (a)

有人可以建议我如何获得此问题的预期输出

【问题讨论】:

  • 预期结果为 [100,190,200] ,每5个元素的累计总和,另外丢弃字符串类型元素

标签: python python-3.x list


【解决方案1】:

首先过滤它们相加的整数:

filtered = [x for x in sample_input if isinstance(x, int)]

result = []
cumsum = 0
for i in range(0, len(filtered), 5):
    cumsum += sum(filtered[i:i + 5])
    result.append(cumsum)

print(result) # [100, 190, 200]

【讨论】:

  • 您的过滤不会尊重 OP 的每组 5 个项目的计数请求。它可能适用于提供的示例,但如果您在第一组中更改 30 to '30' 则不起作用
【解决方案2】:
sample_input = [50, 30, 20, 0, "catch_me", 0, "you_got_me", "did_you_really_catch", 40, 50, "20", 0, 0, 0, 10]
nbr_of_item_per_list = 5


def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

results = []
total = 0
for sample in chunks(sample_input, nbr_of_item_per_list):
    # get the sum of the yield 5 items and add it to the total
    total += sum(value for value in sample if isinstance(value, int))
    results.append(total)

print(results)

输出:

[100, 190, 200]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多