如何在Python中使用IF ALL语句 [英] How to use the IF ALL statement in Python
问题描述
我有一个名为checker(nums)的函数,该函数具有一个稍后将接收列表的参数.我要对该列表进行的操作是检查每个其他元素是否大于或等于前一个元素.
例子:
我有一个列表[1, 1, 2, 2, 3]
,我必须检查它是否满足条件.
既然如此,该函数应该返回True
I have a function named checker(nums) that has an argument that will later receive a list. What i want to do with that list is to check if each other element is greater or equal to the previous one.
Example:
I have a list [1, 1, 2, 2, 3]
and i have to check if it fulfills the condition.
Since it does, the function should return True
我的代码:
def checker(nums):
for x in range(len(nums)):
if x+1<len(nums):
if nums[x] <= nums[x+1] and nums[-1] >= nums[-2]:
return True
这只会运行一次,如果第一个条件为true,则返回True. 我已经看过一份声明,不确定如何使用.
This will only run once and return True if the first condition is true. I've seen a statement if all and am unsure of how to use it.
推荐答案
您的函数可以简化为:
def checker(nums):
return all(i <= j for i, j in zip(nums, nums[1:]))
请注意以下几点:
-
zip
并行遍历其参数,即nums[0]
&检索nums[1]
,然后nums[1]
&nums[2]
等 -
i <= j
执行实际比较. - 用括号
()
表示的生成器表达式确保每次提取一个条件值,即True
或False
.这称为惰性评估. -
all
只需检查所有值是否为.同样,这是懒惰的.如果从生成器表达式延迟提取的值之一是 False
,它将短路并返回False
.
zip
loops through its arguments in parallel, i.e.nums[0]
&nums[1]
are retrieved, thennums[1]
&nums[2]
etc.i <= j
performs the actual comparison.- The generator expression denoted by parentheses
()
ensures that each value of the condition, i.e.True
orFalse
is extracted one at a time. This is called lazy evaluation. all
simply checks all the values areTrue
. Again, this is lazy. If one of the values extracted lazily from the generator expression isFalse
, it short-circuits and returnsFalse
.
为避免为zip
的第二个参数构建列表的开销,可以使用 itertools.islice
.当您的输入是迭代器时,即不能像list
一样切片时,此选项特别有用.
To avoid the expense of building a list for the second argument of zip
, you can use itertools.islice
. This option is particularly useful when your input is an iterator, i.e. it cannot be sliced like a list
.
from itertools import islice
def checker(nums):
return all(i <= j for i, j in zip(nums, islice(nums, 1, None)))
另一个对迭代器友好的选项是使用 itertools
pairwise
食谱,也可以通过第三方 more_itertools.pairwise
:
Another iterator-friendly option is to use the itertools
pairwise
recipe, also available via 3rd party more_itertools.pairwise
:
# from more_itertools import pairwise # 3rd party library alternative
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def checker(nums):
return all(i <= j for i, j in pairwise(nums))
这篇关于如何在Python中使用IF ALL语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!