在Python中切片和汇总字典

时间:2018-03-06 14:06:31

标签: python dictionary slice

我想将字典值加到按键切片的字典部分上。以下示例不在上下文中。我试图将代码减少到必要的东西。问题在最后一行中描述。我尝试切片多个句点并对值进行求和。

  

TypeError:不可用类型:' slice'

stuff = [38, 255, 837]

dict = {}

for t in range(50):
    dict[t] = [(stuff[i] / (1.03)**t) for i in range(3)]

    sum(dict[int(t):int(t+5)][0])

1 个答案:

答案 0 :(得分:0)

词典无法使用您的语法。但是你可以定义一个函数来执行求和:

stuff = [38, 255, 837]

d = {t: [(stuff[i] / (1.03)**t) for i in range(3)] for t in range(50)}

def slice_sum(d, start, end, i=0):
    return sum(v[i] for k, v in d.items() if start <= k < end)

result = {n: slice_sum(d, n, n+5) for n in range(50)}

# {0: 179.24973930679405,
#  1: 174.02887311339228,
#  2: 168.960070983876,
#  3: 164.03890386784076,
#  4: 159.26107171635024,
#  5: 154.62239972461188,