如何在 NumPy 数组中查找连续元素组 [英] How to find the groups of consecutive elements in a NumPy array
本文介绍了如何在 NumPy 数组中查找连续元素组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须对 NumPy 数组中的连续元素进行聚类.考虑下面的例子
I have to cluster the consecutive elements from a NumPy array. Considering the following example
a = [ 0, 47, 48, 49, 50, 97, 98, 99]
输出应该是如下的元组列表
The output should be a list of tuples as follows
[(0), (47, 48, 49, 50), (97, 98, 99)]
这里的区别只是元素之间的区别.如果差异也可以指定为限制或硬编码数字,那就太好了.
Here the difference is just one between the elements. It will be great if the difference can also be specified as a limit or a hardcoded number.
推荐答案
这里有一个小函数可能会有所帮助:
Here's a lil func that might help:
def group_consecutives(vals, step=1):
"""Return list of consecutive lists of numbers from vals (number list)."""
run = []
result = [run]
expect = None
for v in vals:
if (v == expect) or (expect is None):
run.append(v)
else:
run = [v]
result.append(run)
expect = v + step
return result
>>> group_consecutives(a)
[[0], [47, 48, 49, 50], [97, 98, 99]]
>>> group_consecutives(a, step=47)
[[0, 47], [48], [49], [50, 97], [98], [99]]
附言这是纯Python.对于 NumPy 解决方案,请参阅 unutbu 的答案.
P.S. This is pure Python. For a NumPy solution, see unutbu's answer.
这篇关于如何在 NumPy 数组中查找连续元素组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文