[英]Is there a way of include multiple conditions in a Python next function?
一般的想法是我想在每個列表中找到滿足兩個條件中的任何一個的第一個值。 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
您現在的代碼更漂亮,但這會起作用:
a = next((
(x - 1 if x > 4 else x)
for x in the_iterable
if (x > 3 or x > 4)
), default_value)
不, 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
function 無關。
(x for x in expr if predicate(x) or second_predicate(x))
Python 確實有另一個內置 function, 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.
哨兵是一個文字,所以沒有辦法讓它成為多個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.