Skip to main content
 首页 » 编程设计

python之返回超出所有先前元素的元素列表

2025年05月04日22qlqwjy

我是 Python 新手,谁能指出我在代码中犯的错误:

numlist = [3,2,5,5,7,6,1,8,4] 
def peaks(numlist): 
    exceed = [] 
    for elem in numlist: 
        for num in exceed: 
            if elem not in exceed: 
                if num in exceed < elem in numlist: 
                    exceed = exceed + [elem] 
                    print(exceed) 

这是我打算做的:

峰值(数字列表)= = > [3,5,7,8]

感谢帮助!!

请您参考如下方法:

您的代码过于复杂并且有几个问题。

  • if num in exceed < elem in numlist: ??你在比较 bool 值……也许你需要 count相反?
  • for num in exceed:正如 Alex 评论的那样,一开始是空的,然后你测试 if elem not in exceed在这个循环中……过于复杂。

只需保持一个最高的元素值,像这样用一个循环来做:

numlist = [3,2,5,5,7,6,1,8,4] 
maxvalue=numlist[0]-1 
outlist=[] 
for e in numlist: 
    if e<=maxvalue: 
        pass 
    else: 
        maxvalue = e 
        outlist.append(e) 
 
print(outlist) 

结果:

[3, 5, 7, 8]