[英]How to check if there's any odd/even numbers in an Iterable (e.g. list/tuple)?
Suppose we're checking if there's any odd numbers in a list
. 假设我们正在检查是否有在任何的奇数list
。 The most direct way is: 最直接的方法是:
def has_odd(L):
for v in L:
if v % 2 == 1:
return True
return False
The has_odd
function checks if there's any odd numbers in a list
, once an odd number is found, it returns True
. 该has_odd
功能检查,如果有在任何奇数list
,一旦奇数被发现,则返回True
。 But this seems a bit verbose. 但这看起来有点冗长。 A more concise way using reduce
is as follow: 使用reduce
更简洁方法如下:
reduce(lambda res, v: res or bool(v), L, False)
But this will iterate through all elements and is unnecessary, because once an odd number is found the result is surely True
. 但是这将遍历所有元素并且是不必要的,因为一旦找到奇数,结果肯定是True
。
So, are there any other ways to do this? 那么,有没有其他方法可以做到这一点?
You can use the any()
function to reduce the verbosity: 您可以使用any()
函数来减少详细程度:
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> any(n % 2 == 1 for n in l)
True
>>>
Note however, any()
is pretty much the same as you had originally just generalized , so don't expect a speed improvement: 但请注意, any()
与您最初推广的几乎相同 ,所以不要指望速度提升:
def any(iterable):
for element in iterable:
if element:
return True
return False
first of all let's write small indicator function for "oddness" like 首先让我们为“奇怪”写下小指标功能
def is_odd(number):
return number % 2
then we can write our indicator for "has at least one odd number" using any
with imap
/ map
那么我们可以用imap
/ map
any
一个来编写“至少有一个奇数”的指标
Python 2.* Python 2. *
from itertools import imap def has_odd_number(iterable): return any(imap(is_odd, iterable))
Python 3.* Python 3. *
def has_odd_number(iterable): return any(map(is_odd, iterable))
or with generator expression 或与发电机表达
def has_odd_number(iterable):
return any(is_odd(number) for number in iterable)
Examples: 例子:
>>> has_odd_number([0])
False
>>> has_odd_number([1])
True
Another way. 其他方式。 you can use not all()
你not all()
使用not all()
>>> l = [2, 4, 5, 6, 7, 8, 9, 10]
>>> not all(n%2==1 for n in l)
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.