简体   繁体   English

如何在列表中找到所有局部最大值和最小值

[英]How to find all local maxima and minima in a list

I have a list 2,3,4,3,5,9,4,5,6 I want to iterate over the list until I get the first highest number that is followed by a lower number.我有一个列表 2,3,4,3,5,9,4,5,6 我想遍历列表,直到我得到第一个最高的数字,然后是一个较低的数字。 Then to iterate over the rest of the number until I get the lowest number followed by a higher number.然后迭代数字的 rest 直到我得到最小的数字,然后是更高的数字。 Then the next highest highest number that is followed by a lower number.And so on.The result I want is 2,4,3,9,4,6 Here is my last attempt.I seem to be going round in circles然后是下一个最高的数字,然后是一个较低的数字。依此类推。我想要的结果是 2,4,3,9,4,6 这是我的最后一次尝试。我似乎在兜圈子

#!/usr/bin/env python
value = []
high_hold = [0]
low_hold = [20]
num = [4,5,20,9,8,6,2,3,5,10,2,]

def high():
    for i in num:
        if i > high_hold[-1]:
            high_hold.append(i)

def low():
    for i in num:
        if i < low_hold[-1]:
            low_hold.append(i)

high()
a = high_hold[-1]
value.append(a)
high_hold = high_hold[1:]
b = len(high_hold) -1
num = num[b:]

low()
c = len(low_hold) -1
num = num[c:]
value.append(b)
print('5:  ', value, '(this is what we want)')
print(num)

high_hold = [0]

def high():
    for i in num:
        if i > high_hold[-1]:
           high_hold.append(i)

high()
a = high_hold[-1]
print(a)
print('1:  ', high_hold, 'high hold')

How about this (I may have misunderstood your intent).这个怎么样(我可能误解了你的意图)。 Alternate between comparison types while iterating over pairs.在对对进行迭代时在比较类型之间交替。

  • Iterate over pairs迭代对
  • make a comparison做个比较
  • If the comparison is True如果比较为真
    • save the value保存值
    • switch to the other type of comparison切换到其他类型的比较

import operator

num = [4,5,20,9,8,6,2,3,5,10,2,]

curr = operator.lt
nxt = operator.gt

for a,b in zip(num,num[1:]):
    if curr(a,b):
        print(a, end = '|')
        curr,nxt = nxt, curr

Which produces哪个生产

4|20|2|10|

I like OOP so I put it in a class.我喜欢 OOP 所以我把它放在 class 里。 It makes sense for me as we change a state of how we compare, we're looking either for greater than or smaller than, depending on your arbitrary conditions.这对我来说很有意义,因为我们更改了比较方式的 state,我们正在寻找大于或小于,这取决于您的任意条件。

from typing import Sequence, List
import operator


class AshtonSequence:
    def __init__(self, input_sequence: Sequence):
        self.input_sequence = input_sequence
        self.compare = operator.lt

    def change_operator(self) -> None:
        if self.compare is operator.lt:
            self.compare = operator.gt
        else:
            self.compare = operator.lt

    def process(self) -> List[str]:
        answer = []

        current = None

        for i, el in enumerate(self.input_sequence):
            if not current:
                current = el

            # depending if we're looking for lt/gt, if it's gt or lt: assign as current
            elif not self.compare(current, el):
                current = el

                # if it's the last item in the sequence
                if i + 1 == len(self.input_sequence):
                    answer.append(current)

            # otherwise we add it to the answer list, change operator and set current element
            # as a value that we will compare in the future
            else:
                answer.append(current)
                self.change_operator()
                current = el

        return answer


lst = [2, 3, 4, 3, 5, 9, 4, 5, 6]

ans = AshtonSequence(lst).process()
print(ans)

Will give you会给你

[2, 4, 3, 9, 4, 6]

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

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