【发布时间】:2015-04-30 02:23:44
【问题描述】:
我有一个 Python 字典列表,表示国家代码和不同服务器的命中百分比。
[{'country': 'BR', 'values': {'Server1': [100.0, 100.0]}},
{'country': 'IE', 'values': {'Server1': [61.7868], 'Server2': [38.2132]}},
{'country': 'US', 'values': {'Server1': [82.19], 'Server2': [100.0]}}]
我想将其转换为保持百分比不变的单个值。所以我将列表中的值加起来,然后除以它们的长度,如
for key_dict in resp:
averages = {}
for name, numbers in key_dict['values'].items():
averages[name] = sum(numbers) / len(numbers)
key_dict['values'] = averages
但在大多数情况下,这并不能算出正确的百分比。例如,上述解决方案将导致。
[{'country': 'BR', 'values': {'Server1': [100.0]}},
{'country': 'IE', 'values': {'Server1': [61.7868], 'Server2': [38.2132]}},
{'country': 'US',
'values': {'Server1': [100.0, 92.8571, 100.0, 100.0, 18.1078],
'Server2': [100.0, 100.0]}}]
很明显 'USsum both theServer1andServer2` 超过 100 。我如何在python中清楚地划分百分比。
【问题讨论】:
-
我上次检查的时候,100.0和82.19都没有超过100。请您澄清一下问题
-
总和超过 100 ,理想情况下两台服务器的总和应为 100 以获得百分比拆分。
-
你能澄清一下这个问题吗?为什么国家
'BR'中'Server1'的值有两个值,而其他所有值都为1?您能否为我们提供的示例输入提供您想要的示例输出
标签: python math numpy dictionary percentage