且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何按范围对列表元素进行分组/计数

更新时间:2023-02-19 17:50:59

您可以使用 bisect module和 collections.Counter

 >&gt ;> import bisect 
>>>>从集合导入计数器
>>>>计数器(x [bisect.bisect_left(x,item)] for y)
计数器({10:3,30:2,20:1})
/ pre>

If my x list and y list are:

x = [10,20,30]
y = [1,2,3,15,22,27]

I'd like a return value to be a dictionary that has a count of the elements that were less than the x value:

{
    10:3,
    20:1,
    30:2,
}

I have a very large list, so I was hoping there was a better way to do it that didn't involve a slow nested for loop. I've looked at collections.Counter and itertools and neither seem to offer a way of grouping. Is there a built-in that can do this?

You can use the bisect module and collections.Counter:

>>> import bisect
>>> from collections import Counter
>>> Counter(x[bisect.bisect_left(x, item)] for item in y)
Counter({10: 3, 30: 2, 20: 1})