Python检测列表中的拐点并替换

2024-04-19 16:42:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这个标题实际上有误导性,但我不知道如何用一句话来描述我的问题。我不关心拐点,但我关心的是值从x>;1至x<;1.

考虑以下数组:

a = np.array([0.683, 0.819, 0.678, 1.189, 1.465, 0.93 , 0.903, 1.321, 1.321, 0.785, 0.875])

# do something... and here's what I want:

np.array([True, False, False, False, False, True, True, False, False, True, True])

规则如下:

  1. 数组中的第一个点是起点,并且始终标记为True
  2. 为了将值标记为True,它必须小于1(x<;1)
  3. 但是,即使某个值小于1,如果该值介于第一个值小于1和第一个值大于1之间,请将其标记为False

如果我的解释不合理,下面是我想做的事情:

enter image description here

数组a中的十进制值只是比率:当前点/上一点。如何在Python中实现这一点


Tags: and标记ltgtfalsetrue标题np
1条回答
网友
1楼 · 发布于 2024-04-19 16:42:57

我输入的代码将按照您的要求执行。不幸的是,它不使用列表理解。 我做的第一件事就是编写一个函数,找到第一个小于零的值和第一个大于零的值的索引

import numpy as np
a = np.array([0.683, 0.819, 0.678, 1.189, 1.465, 0.93 , 0.903, 1.321, 1.321, 0.785, 0.875])

### if a number is below ONE but in a position between the first true below zero and the first false above zero
### then it's false

## find the two indexes of the first value below 1 and the first value above 1
def find_indx(a):

    first_min=0
    for i in range(len(a)):
        if(a[i]<1):
            first_min=i
            break
    first_max=0
    for i in range(len(a)):
        if(a[i]>1):
            first_max=i
            break
    return([first_min,first_max])

使用此函数,可以将低于零但介于第一个低于零和第一个高于零之间的值设置为false。 这两个索引存储在“false_range”中

一旦你做到了这一点,就很容易了。第一点总是正确的。 如果索引介于“false_range”和零以下,则它们将变为false。 如果点在“假_范围”之外,则其值取决于它们是高于1还是低于1

false_range=find_indx(a)

truth_list=[]
for i in range(len(a)):
    ## the first value is always true
    if(i==0):
        truth_list.append(True)
    else:
        ## if the index is between the false_range and 
        ## this value is below 1 assign False
        if(i>false_range[0] and i<false_range[1] and a[i]<1):
            truth_list.append(False)
        ## in all the other cases it depends only if the value is below or above zero
        elif(a[i]>1):
            truth_list.append(False)
        elif(a[i]<1):
            truth_list.append(True)


print(truth_list)

[True, False, False, False, False, True, True, False, False, True, True]

打印的列表与您提供的列表相对应,但请在使用前测试此解决方案

相关问题 更多 >