您可以使用bisect.bisect(...)
實現這一爲:
from bisect import bisect
import random
randon_nums = [random.randint(0,100) for _ in xrange(100)]
bucket = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # can also be created using:
# range(10, 101, 10)
randon_nums.sort() # sort the initial list in order to use it with `bisect`
counts = []
last_bucket_count = 0 # to track the count of numbers in last calculated bucket
for range_max in bucket:
i = bisect(randon_nums, range_max, end_index)
counts.append(i - last_bucket_count)
last_bucket_count = i
樣品試驗:
當random_nums
值是:
>>> randon_nums
[0, 1, 4, 5, 5, 5, 5, 6, 7, 7, 8, 8, 10, 10, 11, 11, 12, 13, 13, 13, 16, 17, 18, 18, 18, 18, 19, 20, 21, 22, 24, 24, 25, 25, 26, 26, 26, 26, 26, 29, 30, 30, 31, 33, 37, 37, 38, 42, 42, 43, 44, 44, 47, 47, 49, 51, 52, 55, 55, 57, 57, 58, 59, 63, 63, 63, 63, 64, 64, 65, 66, 67, 68, 71, 73, 73, 73, 74, 77, 79, 82, 83, 83, 83, 84, 85, 87, 87, 88, 89, 89, 90, 92, 93, 95, 96, 98, 98, 99, 99]
上述程序返回count
爲:
>>> counts
[ 14, 14, 14, 5, 8, 8, 10, 7, 12, 8]
# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
# 0-10 10-20 20-30 30-40 40-50 50-60 60-70 70-80 80-90 90-100
感謝您提供的信息。 – Nourolah
非常歡迎。 –