【问题标题】:Is there a way of include multiple conditions in a Python next function?有没有办法在 Python 的 next 函数中包含多个条件?
【发布时间】:2021-05-01 17:18:06
【问题描述】:

一般的想法是我想在每个列表中找到满足两个条件中的任何一个的第一个值。 IE。: '

a = next((x for x in the_iterable if x > 3), default_value)

但是,我希望它有多个条件,例如:

a = next((x for x in the_iterable if x > 3 or x-1 for x in the_iterable if x>2), default_value)

我的代码现在看起来像:

a = []
for x in iterable:
  if x>3:
    a.append(x)
    break
  elif x>4:
    a.append(x-1)
    break

【问题讨论】:

  • 你现在的代码比下一个丑陋的代码漂亮多了。我建议你使用它。
  • 我认为,您的代码 id 中的一个条件与下一条语句中的数学无关,所以 if 2<x<=3:x.append(x-1) break elif x>3: a.append(x) break
  • 是的,语句没有添加,这不是真正的问题,只是打了个大概的思路,og的要复杂得多,我的错。

标签: python conditional-statements next


【解决方案1】:

没有。 next 根本没有条件。它只需要一个迭代器和一个可选的默认值:

Help on built-in function next in module builtins:

next(...)
    next(iterator[, default])
    
    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.

所以你不仅不能包含多个条件,甚至不能包含一个。

如果您的意思是问是否可以在推导式或生成器表达式中包含多个条件,那么这实际上与 next 函数无关。

(x for x in expr if predicate(x) or second_predicate(x))

Python 确实有另一个内置函数 iter,它有一个非常简单的内置谓词,称为 sentinel

Help on built-in function iter in module builtins:

iter(...)
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator
    
    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.

sentinel 是一个字面量,因此无法将其设为多个值。

【讨论】:

  • 不光你错了,你是在误导别人,接下来可以有一个条件,可能我们对'条件'的理解不是一样的,但是看看问题中的初始代码。
  • @Ferzimo 您询问了next 函数,但这不是条件适用的地方。条件在生成器表达式中。无论您是否直接使用next,它都将适用。这就是为什么有两对括号,而不仅仅是一个用于函数应用程序的括号。您当然可以在生成器表达式中应用多个条件,将它们与布尔运算符(如 andor)结合使用。
【解决方案2】:

您现在的代码更漂亮,但这会起作用:

a = next((
 (x - 1 if x > 4 else x) 
 for x in the_iterable 
 if (x > 3 or x > 4)
), default_value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-06
    • 2022-11-27
    • 2021-06-29
    • 1970-01-01
    • 2019-12-24
    相关资源
    最近更新 更多