代码审查在索引 Python 处拍摄快照的列表累计总数

问题描述 投票:0回答:1

另一个关于累计总数的问题。考虑以下代码:

json_message = {'result':[[12,  234],  [53,  45],  [3,  425],  [74,  12],  [3,  678],  [2,  42],  [12,  234],  [1,  66],  [6,  85],  [5,  73],  [12,  84],  [6,  24],  [98,  23],  [34,  4],  [82,  253]]}
total = 0
totals = [{'length': 1, 'total': 0},  {'length': 4, 'total': 0}, {'length': 7, 'total': 0}, {'length': 10, 'total': 0}, {'length': 15, 'total': 0}]

for index,  item in enumerate(json_message['result'][::-1]):
    total += round(float(item[1]),  2)
    if index == totals[0]['length']-1:
        totals[0]['total'] = total
    elif index == totals[1]['length']-1:
        totals[1]['total'] = total
    elif index == totals[2]['length']-1:
        totals[2]['total'] = total
    elif index == totals[3]['length']-1:
        totals[3]['total'] = total
    elif index == totals[4]['length']-1:
        totals[4]['total'] = total

print(totals)

我在 json_message['result'] 中有一个列表列表,我想获得每个列表中第二个 int 的总和,从而获得每个第 n 个索引(由长度表示)的累积总数,反之亦然。代码有效,只是寻找更优雅的解决方案。

我也尝试过

json_message = {'result':[[12,  234],  [53,  45],  [3,  425],  [74,  12],  [3,  678],  [2,  42],  [12,  234],  [1,  66],  [6,  85],  [5,  73],  [12,  84],  [6,  24],  [98,  23],  [34,  4],  [82,  253]]}
total = 0
totals = [{'length': 1, 'total': 0},  {'length': 4, 'total': 0}, {'length': 7, 'total': 0}, {'length': 10, 'total': 0}, {'length': 15, 'total': 0}]

ind = (1, 4, 7, 10)

for index,  item in enumerate([[x[1] for x in json_message['result'][::-1]][start:stop] for start,stop in zip((0,)+ind, ind+(len(json_message['result']),))]):
for x in item:
    total += round(float(x),  2)
totals[index]['total'] = total

print(totals)

这也可行,但肯定更短,没有我想要的那么优雅。它的工作原理是分离列表中的第二个 int 并通过列表理解反转它们。然后将它们分成 5 个列表并求每个列表的累积和。

专家的建议将不胜感激。谢谢。

python list indexing list-comprehension cumulative-sum
1个回答
0
投票

您可以使用

numpy
模块:

x = np.array(json_message['result'][::-1]).T[1]
# json_message['result'][::-1] reverses the 2d list
# .T gives us the transpose of the 2d array, in your case
# to make it easier to get 2nd element, i.e., 2nd column here

for d in totals:
    d['total'] = round(float(sum(x[:d['length']])), 2) # Don't really know why there is round(float(x)) in your code
print(totals)
© www.soinside.com 2019 - 2024. All rights reserved.