计算间隔之间的值数 [英] Counting number of values between interval
问题描述
在python中,有没有一种有效的方法来计算数字数组在特定间隔之间的时间?我将使用的间隔数可能会变得很大
Is there any efficient way in python to count the times an array of numbers is between certain intervals? the number of intervals i will be using may get quite large
喜欢:
mylist = [4,4,1,18,2,15,6,14,2,16,2,17,12,3,12,4,15,5,17]
some function(mylist, startpoints):
# startpoints = [0,10,20]
count values in range [0,9]
count values in range [10-19]
output = [9,10]
推荐答案
您将必须至少迭代一次该列表.
you will have to iterate the list at least once.
以下解决方案适用于实现比较的任何序列/间隔(<
,>
等),并使用
The solution below works with any sequence/interval that implements comparision (<
, >
, etc) and uses bisect
algorithm to find the correct point in the interval, so it is very fast.
它将适用于浮点数,文本或其他内容.只需传递一个序列和间隔列表即可.
It will work with floats, text, or whatever. Just pass a sequence and a list of the intervals.
from collections import defaultdict
from bisect import bisect_left
def count_intervals(sequence, intervals):
count = defaultdict(int)
intervals.sort()
for item in sequence:
pos = bisect_left(intervals, item)
if pos == len(intervals):
count[None] += 1
else:
count[intervals[pos]] += 1
return count
data = [4,4,1,18,2,15,6,14,2,16,2,17,12,3,12,4,15,5,17]
print count_intervals(data, [10, 20])
将打印
defaultdict(<type 'int'>, {10: 10, 20: 9})
这意味着您有10个值<10和9个值< 20.
Meaning that you have 10 values <10 and 9 values <20.
这篇关于计算间隔之间的值数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!