python 列表中值的百分比分布

Percentage distribution of values in a python list

假设我们有以下列表。此列表包含 REST 服务器在流量 运行.

中的响应时间

[1, 2, 3, 3, 4, 5, 6, 7, 9, 1]

我需要以下输出

在特定时间(毫秒)内处理的请求的百分比

50% 3

60% 4

70% 5

80% 6

90% 7

100% 9

我们如何才能在 python 中完成它?这是 apache bench 类型的输出。所以基本上可以说是 50%,我们需要在列表中找到低于 50% 列表元素的点,依此类推。

您可以尝试这样的操作:

responseTimes = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
for time in range(3,10):
    percentage = len([x for x in responseTimes if x <= time])/(len(responseTimes))
    print(f'{percentage*100}%')

"So basically lets say at 50%, we need to find point in list below which 50% of the list elements are present and so on"

responseTimes = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
percentage = 0
time = 0
while(percentage <= 0.5):
    percentage = len([x for x in responseTimes if x <= time])/(len(responseTimes))
    time+=1

print(f'Every time under {time}(ms) occurrs lower than 50% of the time')

您基本上需要计算已排序响应时间的累积比率。

from collections import Counter

values = [1, 2, 3, 3, 4, 5, 6, 7, 9, 1]
frequency = Counter(values) # {1: 2, 2: 1, 3: 2, ...}
total = 0
n = len(values)

for time in sorted(frequency):
    total += frequency[time]
    print(time, f'{100*total/n}%')

这将以相应的比例打印所有时间。

1 20.0%
2 30.0%
3 50.0%
4 60.0%
5 70.0%
6 80.0%
7 90.0%
9 100.0%