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

2024-06-17 13:11:45 发布

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

我有一张清单2,3,4,3,5,9,4,5,6 我想迭代列表,直到得到第一个最高的数字,然后是一个较低的数字。然后对其余的数字进行迭代,直到得到一个最小的数字,然后是一个较大的数字。然后是下一个最高的数字,后面是一个较低的数字。依此类推。我想要的结果是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')

Tags: in列表forlenifvaluedef数字
2条回答

这个怎么样(我可能误解了你的意图)。在对进行迭代时,在比较类型之间交替

  • 成对迭代
  • 比较
  • 如果比较是真的
    • 保存值
    • 切换到其他类型的比较

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

产生

4|20|2|10|

我喜欢OOP,所以我把它放在课堂上。这对我来说是有意义的,因为我们改变了比较的状态,我们寻找大于或小于,这取决于你的任意条件

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)

我会给你

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

相关问题 更多 >