python - 在python中对数组列表进行分类

标签 python arrays logic python-2.7

我正在帮助我的 friend 在 python 中做逻辑算法,但我还没有找到最好的解决方案。

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

x = array[0,1,2,3,4,3,2,3,-2,-4,-7,2,2]

他想对 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

规则很简单:

  1. if the value keep increasing (like example above: 0,1,2,3,4) they put in one array
  2. if the value keep decreasing (like example above: 3,-2,-4,-7) they put in one array
  3. but, if there is a sudden change in value pattern such as example above: from the increasing value (0,1,2,3,4) suddenly the next value is decreasing. the new array will be made and put the last increasing value which is (4) and monitor the next value, whether it is decreasing value or not. If yes, they will be put in one array. example :array([4,3,2])
  4. if the the value is remain the same (like example above, from 2 to 2). they will be put in one array.

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

#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!'

最好的问候,

格伦

最佳答案

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

array([3,-2]) #decreasing value
array([-2,-4,-7]) #decreasing value

为什么这些是分开的?

到目前为止,我将发布我的答案,它给出了正确的结果,但该部分除外,因为我看不到它背后的逻辑。为简单起见,此示例使用列表和元组,但您可以根据需要将其更改为使用数组。

>>> 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)]

关于python - 在python中对数组列表进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633831/

相关文章:

javascript - 使用 forEach 在多个数组中搜索字符串

ruby-on-rails - rails 逻辑!预购广告,如何存储信息?

python - 坚持Boost-Python教程(Boost 1_64_0、Python3.6和msvc 14.0)

python - py脚本从mysql数据库写入xlsx文件

javascript - 在 react 模板中提取对象数组中的对象项

python - 填充 3d numpy 数组的某些索引

javascript - & 1 JavaScript。它是如何工作的?聪明还是善良?

检查命令行参数中的任何字符是否不是 '1' 或 C 中的 '0'

python - 性能 - 为什么具有范围的素数生成算法比使用素数列表快得多?

python - pyinstaller 捆绑图像的文件路径?