以下是一个示例代码,用于按降序计算列表的频率以及高于其的值的百分比:
from collections import Counter
def compute_frequency_and_percentage(lst):
# 计算列表中每个元素的频率
frequency = Counter(lst)
# 按降序排序并计算高于每个元素的值的百分比
sorted_items = sorted(frequency.items(), key=lambda x: x[0], reverse=True)
total_count = len(lst)
result = []
higher_percentage = 0
for item, count in sorted_items:
percentage = count / total_count * 100
result.append((item, count, percentage, higher_percentage))
higher_percentage += percentage
return result
# 示例输入
lst = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
result = compute_frequency_and_percentage(lst)
for item, count, percentage, higher_percentage in result:
print(f"元素 {item} 出现次数为 {count},频率为 {percentage:.2f}%,高于其的值的百分比为 {higher_percentage:.2f}%")
示例输出:
元素 4 出现次数为 1,频率为 10.00%,高于其的值的百分比为 100.00%
元素 3 出现次数为 2,频率为 20.00%,高于其的值的百分比为 90.00%
元素 2 出现次数为 3,频率为 30.00%,高于其的值的百分比为 70.00%
元素 1 出现次数为 4,频率为 40.00%,高于其的值的百分比为 40.00%
该示例代码使用了Python的collections库中的Counter类来计算列表中每个元素的频率。然后,使用sorted函数将频率从高到低进行排序,并计算高于每个元素的值的百分比。最后,将结果以元素、频率、百分比和高于其的值的百分比的形式返回。
上一篇:按降序进行查找的VLOOKUP
下一篇:按降序计算字母频率