gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:51:13 24 4
gpt4 key购买 nike

我正在帮助我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com