gpt4 book ai didi

python - 计算值出现在值范围内的次数

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:29 24 4
gpt4 key购买 nike

如何输出一个列表,该列表计算并显示不同值适合某个范围的次数?

根据下面的示例,输出将是 x = [0, 3, 2, 1, 0] 因为有 3 个专业分数 (11, 24, 44),2 个冠军分数 (101, 888),和 1 个国王分数 (1234)

- P1 = 11 
- P2 = 24
- P3 = 44
- P4 = 101
- P5 = 1234
- P6 = 888

totalsales = [11, 24, 44, 101, 1234, 888]

这里是销量对应的排名:

Sales___________________Ranking
0-10____________________Noob
11-100__________________Pro
101-1000________________Champion
1001-10000______________King
100001 - 200000__________Lord

最佳答案

这是一种方法,假设您的值是整数并且范围不重叠。

from collections import Counter

# Ranges go to end + 1
score_ranges = [
range(0, 11), # Noob
range(11, 101), # Pro
range(101, 1001), # Champion
range(1001, 10001), # King
range(10001, 200001) # Lord
]
total_sales = [11, 24, 44, 101, 1234, 888]

# This counter counts how many values fall into each score range (by index).
# It works by taking the index of the first range containing each value (or -1 if none found).
c = Counter(next((i for i, r in enumerate(score_ranges) if s in r), -1) for s in total_sales)
# This converts the above counter into a list, taking the count for each index.
result = [c[i] for i in range(len(score_ranges))]
print(result)
# [0, 3, 2, 1, 0]

关于python - 计算值出现在值范围内的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com