Python|区间列表求和
有许多方法可以用元素初始化列表,但有时需要以切片的方式用数字初始化列表并找到其总和。这可以是自定义的,因此这方面的知识可以派上用场。让我们讨论一些可以做到这一点的方法。
方法 #1:使用列表理解 + enumerate() + sum()
列表推导可以完成可能的迭代部分,枚举可以帮助逻辑部分和检查列表中所需的有效元素。 sum() 用于执行求和。
# Python3 code to demonstrate
# Interval List Summation
# using list comprehension + enumerate() + sum()
# initializing lists
test_list = list(range(50))
# printing original list
print ("The original list is : " + str(test_list))
# interval elements
N = 5
# interval difference
K = 15
# using list comprehension + enumerate() + sum()
# Interval List Summation
res = sum([i for j, i in enumerate(test_list) if j % K < N ])
# printing result
print ("The modified range sum list : " + str(res))
The original list is : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
The modified range sum list : 490
方法#2:使用itertools.compress() + itertools.cycle() + sum()
上述两个函数可以结合起来,以方便解决所讨论的问题。循环函数可以用于重复任务,而压缩函数在将片段组合在一起时可能是有益的。 sum() 用于执行求和。
# Python3 code to demonstrate
# Interval List Summation
# using itertools.compress() + itertools.cycle() + sum()
from itertools import compress, cycle
# initializing lists
test_list = list(range(50))
# printing original list
print ("The original list is : " + str(test_list))
# interval elements
N = 5
# interval difference
K = 15
# using itertools.compress() + itertools.cycle() + sum()
# Interval List Summation
func = cycle([True] * N + [False] * (K - N))
res = sum(list(compress(test_list, func)))
# printing result
print ("The modified range sum list : " + str(res))
The original list is : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
The modified range sum list : 490