在由三个或更多零分隔的部分中对列表元素进行计数和求和

我有一个整数列表,我想根据某个条件将它们分开。我想获取列表元素的总和和计数,当三个或更多连续元素等于 0 时停止;然后 sum 和 count 订单从停止的地方重新开始。

例如,列表的一部分是:

[8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 8, 0, 0, 2, 0, 0, 0, 6, 0, 0]
[8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 8, 0, 0, 2, 0, 0, 0, 6, 0, 0]

该过程将是:

所以我想要的输出是:

[[14, 5], [8, 3], [10, 4], [6, 3]]

到目前为止我所写的计算总和没问题,但我的问题是部分内的零不计入长度。

当前(不正确)输出:

[[14, 5], [8, 2], [10, 2], [6, 2]]

代码:

arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 8, 0, 0, 2, 0, 0, 0, 6, 0, 0]
result = []
summed, count = 0, 0
for i in range(0, len(arr) - 2):
    el, el1, el2 = arr[i], arr[i + 1], arr[i + 2]
    if el != 0:
        summed = summed + el
        count = count + 1
    if el == 0 and el1 == 0 and el2 == 0:
        if summed != 0:
            result.append([summed, count])
            summed = 0
            count = 0
    elif i == len(arr) - 3:
        summed = el + el1 + el2
        count = count + 1
        result.append([summed, count])
        break

print(result)

回答

很难理解你的代码是做什么的。使用字符串似乎更简单易读,您的输出只需两行即可实现(感谢@CrazyChucky 的改进):

import re 

arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 8, 0, 0, 2, 0, 0, 0, 6, 0, 0]
# Convert to String by joining integers, and split into substrings, the separator being three zeros or more
strings = re.split(r'0{3,}', ''.join(str(i) for i in arr))
# Sums and counts using list comprehensions
output = [[sum(int(x) for x in substring), len(substring)] for substring in strings]

输出:

>>>output
>>>[[14, 5], [8, 3], [10, 4], [6, 3]]

请记住,可读性始终是任何代码中最重要的因素。一个人应该第一次阅读你的代码并理解它是如何工作的。

如果完整列表包含多于一位的数字,您可以执行以下操作:

# Convert to String by joining integers, seperating them by a commade, and split into substrings, the separator being three zeros or more
strings = re.split(r',?(?:0,){3,}', ','.join(str(i) for i in arr))
# Make a list of numbers from those strings
num_lists = [string.split(',') for string in strings]
# # Sums and counts using list comprehensions
output = [[sum(int(x) for x in num_list), len(num_list)] for num_list in num_lists]

  • @MostafaGomaa The output only contains integers. I am not sure what you mean by 'data'. I am only using strings temporarely to find the output.

以上是在由三个或更多零分隔的部分中对列表元素进行计数和求和的全部内容。
THE END
分享
二维码
< <上一篇
)">
下一篇>>