如何按范围对列表元素进行分组/计数 [英] How to group / count list elements by range

查看:426
本文介绍了如何按范围对列表元素进行分组/计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的x列表和y列表是:

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

我想要一个返回值是一个字典,其数量小于x值:

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

我有一个非常大的列表,所以我希望有一个更好的方式来做,没有涉及一个缓慢的嵌套for循环。我看过collections.Counter和itertools,并没有提供一种分组的方法。是否有内置的可以做到这一点?

解决方案

您可以使用 bisect module和 collections.Counter

 >> ;> 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})

这篇关于如何按范围对列表元素进行分组/计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆