如何对列表中彼此之间处于n内的元素进行分组 [英] How to group elements of a list that are within n of each other

查看:99
本文介绍了如何对列表中彼此之间处于n内的元素进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

list_1 = []
list_2 = [1.0, 3.0, 3.15, 1.03, 6.0, 7.0]

我想对这个列表进行排序,并合并彼此之间(在这种情况下)0.15之内的元素.

And I want to sort through this list and merge elements that are within (in this case) 0.15 of each other.

因此,到此结束,list_1与包含以下值:

So by the end of this, list_1 with contain the following values:

[[1.0, 1.03],[3.0, 3.15]]

因为1.01.03彼此在0.15之内,而3.03.15也在彼此0.15之内.

Because 1.0, 1.03 were within 0.15 of each other and 3.0, 3.15 were also within 0.15 of each other.

这还可以不仅仅是成对的,例如,如果我有3.16,它在3.15的范围内,那么它将被添加到组中,即:

This can also be more than just pairs, so for instance if I had 3.16, that is within range of 3.15, so it would be added to the group, ie:

list_2 = [1.0, 3.0, 3.15, 1.03, 6.0, 7.0, 3.16]

输出:

[[1.0,1.03],[3.0,3.15,3.16]]

我该怎么做?

感谢您的帮助!

推荐答案

networkx在这里过大.只需先对列表排序,然后在上一个和当前之间的差异大于您的增量时进行迭代并产生一个块.

networkx is overkill here. Just sort the list first, then iterate and yield off a chunk when the difference between previous and current is larger than your delta.

>>> list_2 = [1.0, 3.0, 3.15, 1.03, 6.0, 7.0, 3.16]
>>> list_2.sort()
>>> delta = 0.15
>>> list_1 = []
>>> prev = -float('inf')
>>> for x in list_2:
...     if x - prev > delta:
...         list_1.append([x])
...     else:
...         list_1[-1].append(x)
...     prev = x
...
>>> list_1
[[1.0, 1.03], [3.0, 3.15, 3.16], [6.0], [7.0]]
>>> [x for x in list_1 if len(x) > 1]
[[1.0, 1.03], [3.0, 3.15, 3.16]]

这篇关于如何对列表中彼此之间处于n内的元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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