简体   繁体   English

python在列表中找到大于左和右的数字

[英]python find the num in list greater than left and right

The question is use iterator to find the num from list who is greater than the nums in left and right 问题是使用迭代器从列表中查找大于左右数字的数字

For example, select([0,1,0,2,0,3,0,4,0]) return [1,2,3,4] 例如,select([0,1,0,2,0,3,0,4,0])返回[1,2,3,4]

My first try is 我的第一次尝试是

def select(iterable):
    answer = []
    it = iter(iterable)

    try:
        v2 = next(it)
        while True:
            v1,v2= v2,next(it)
            if v2>v1 and v2>next(it):
                answer.append(v2)
    except StopIteration:
         pass
    return answer

This code fails. 此代码失败。 I think the next(it) in the while loop would be the same iterator,but the next() still iter next one in the code. 我认为while循环中的next(it)将是相同的迭代器,但next()仍会迭代代码中的下一个。

then I change the code to below one, it works. 然后我将代码更改为以下代码,它可以工作。

try:
    v1,v2,v3 = next(it),next(it),next(it)
    while True:
        if v2>v1 and v2>v3:
            answer.append(v2)
        v1,v2,v3 = v2,v3,next(it)
except StopIteration:
     pass

Can someone explain what is difference happen here? 有人可以解释这里有什么区别吗?

There are two issues with the first snippet: 第一个代码段存在两个问题:

  1. Every time you call next(it) , it advances the iterator. 每次调用next(it) ,它都会推进迭代器。 You have to store the returned value if you want to access it more than once. 如果要多次访问返回值,则必须存储它。 Calling next(it) again won't do that; 再次调用next(it)不会这样做。 it will advance the iterator yet again. 它将再次推进迭代器。
  2. Even if the first point weren't an issue, the following would still be problematic: 即使第一点不是问题,但以下问题仍然存在:

      if v2>v1 and v2>next(it): 

    The issue here is short-circuit evaluation . 这里的问题是短路评估 Depending on whether v2>v1 , this may or may not advance the iterator. 取决于v2>v1 ,这可能会或可能不会使迭代器前进。

The error lies in this line: 错误在于此行:

if v2>v1 and v2>next(it):

Your calling next(it), but you don't store the return value. 您的调用next(it),但是您不存储返回值。 You just compare it to the v2. 您只需将其与v2进行比较即可。 So the value gets skipped. 因此,该值将被跳过。

edit: 编辑:

Btw, if you compare multiple values, the following comparison is much more cleaner: 顺便说一句,如果您比较多个值,则以下比较会更简洁:

 if v1 < v2 > v3:

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

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