简体   繁体   English

整数数组中不相等元素之间的最小差

[英]Minimum difference between non-equal elements in integer array

I do have a list with integer arrays where every element has value <= 100. I need to figure out the smallest difference between non-equal elements for every array. 我确实有一个包含整数数组的列表,其中每个元素的值<=100。我需要找出每个数组的不相等元素之间的最小差异。 So far I have the following ( item represents one array): 到目前为止,我有以下内容( item代表一个数组):

unq  = numpy.unique(item)
mind = numpy.amin(
        (numpy.append(unq, [999]))
       -(numpy.append([-999],unq))
       )

Using numpy I first get sorted array of unique elements. 首先使用numpy获得唯一元素的排序数组。 After adding high positive number at the end and high negative number at the beginning I substract these two arrays and get minimum value. 在结尾处添加高正数并在开始处添加高负数后,我将这两个数组相减并得到最小值。

Is there any faster way to do this? 有没有更快的方法可以做到这一点?

I think your solution is ok except that instead of using numpy.append you would better use np.diff , like np.diff(np.unique(a)) : 我认为您的解决方案是可以的,除了可以使用np.diffnp.diff(np.unique(a))而不是numpy.append

In [1]: import numpy as np

In [2]: a = np.random.randint(0,100,size=50)

In [4]: np.unique(a)
Out[4]: 
array([ 0,  2,  3,  5,  7,  8, 15, 18, 20, 22, 23, 27, 30, 31, 32, 33, 37,
       38, 42, 43, 45, 48, 49, 57, 59, 62, 65, 70, 74, 75, 76, 78, 79, 80,
       83, 84, 88, 91, 93, 94, 96, 98])

In [5]: np.diff(np.unique(a))
Out[5]: 
array([2, 1, 2, 2, 1, 7, 3, 2, 2, 1, 4, 3, 1, 1, 1, 4, 1, 4, 1, 2, 3, 1, 8,
       2, 3, 3, 5, 4, 1, 1, 2, 1, 1, 3, 1, 4, 3, 2, 1, 2, 2])

In [6]: np.diff(np.unique(a)).min()
Out[6]: 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM