在python中分类数组列表

glw*_*iam 2 python arrays logic python-2.7

我正在帮助我的朋友在python中进行逻辑算法,但我还没有找到最好的解决方案.

首先,我有一个数组列表:

x = array[0,1,2,3,4,3,2,3,-2,-4,-7,2,2]
Run Code Online (Sandbox Code Playgroud)

他想对x进行分类,所以输出变成这样:

array([0,1,2,3,4]) # increasing value
array([4,3,2]) #decreasing value
array([2,3]) # increasing value
array([3,-2,-4,-7]) #decreasing value
array([-7,2]) # increasing value
array([2,2])  # remain_the_same_value
Run Code Online (Sandbox Code Playgroud)

规则很简单:

  1. 如果值继续增加(如上例:0,1,2,3,4),则将它们放入一个数组中
  2. 如果值继续减小(例如上面的例子:3,-2,-4,-7),它们就放在一个数组中
  3. 但是,如果价值模式突然发生变化,例如上面的例子:从增加值(0,1,2,3,4)突然下一个值正在减少.将生成新数组并将最后一个增加的值(即4)监视下一个值,无论它是否为递减值.如果是,它们将被放入一个阵列中.示例:array([4,3,2])
  4. 如果值保持不变(例如上面的例子,从2到2).它们将放在一个阵列中.

这是我到目前为止所做的,但距离解决方案还很远

#categorize which types of input
if len(x) > 2 :
    for i in range(len(x)) :
        if (x[i+1]-x[i]) > 0 and i+i < len(x) : # for increasing x value

        elif (x[i+1]-x[i]) < 0 and i+i < len(x) : # for decreasing x value

        elif (x[i+1]-x[i]) == 0 and i+i < len(x) : # for foward direction of vehicle

        else :
            print 'ERROR : check the input coordinates once again!'
Run Code Online (Sandbox Code Playgroud)

最好的祝福,

格伦

jam*_*lak 5

首先我想说我不明白你问题的一部分,

array([3,-2]) #decreasing value
array([-2,-4,-7]) #decreasing value
Run Code Online (Sandbox Code Playgroud)

为什么这些是分开的?

到目前为止,我将发布我的答案,除了该部分之外,它给出了正确的结果,因为我没有看到它背后的逻辑.此示例使用列表和元组来简化,但如果需要,可以将其更改为使用数组.

>>> from itertools import groupby
>>> data = [0,1,2,3,4,3,2,3,-2,-4,-7,2,2]
>>> def slope(a,b): #Returns 1 for inc, 0 for equal and -1 for dec
        return (a > b) - (a < b) 

>>> def groups(nums):
        for k,v in groupby(zip(nums,nums[1:]), lambda (x,y): slope(x,y)):
            yield next(v) + tuple(y for x,y in v) #Using itertools.chain this can be written as tuple(chain(next(v),(y for x,y in v)))


>>> list(groups(data))
[(0, 1, 2, 3, 4), (4, 3, 2), (2, 3), (3, -2, -4, -7), (-7, 2), (2, 2)]
Run Code Online (Sandbox Code Playgroud)