Python:找出元组是否包含偶数的函数吗? [英] Python: Function to find out if a tuple contains even numbers?
本文介绍了Python:找出元组是否包含偶数的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想要的是一个函数,该函数从用户那里获取元组输入,然后确定该元组是否包含偶数.我想知道如何使用for或while循环.我已经尝试过了,但是代码不起作用.我有一些东西,但是它不起作用:
So what I want is a function that gets a tuple input from a user and then figures out if that tuple contains an even number. I want to know how to do it with a for or while loop. I've tried it but the code doesn't work. I've kind of got something but it's not working:
def ifEven(x):
i = -1
if isinstance(x, tuple):
while i < len(x):
for i in x:
i = i + 1
if x[i] % 2 == 0:
return True
else:
return False
推荐答案
You should read the documentation about for
statement in Python: https://docs.python.org/2/tutorial/controlflow.html#for-statements.
这是一个有效的代码:
def ifEven(x):
if isinstance(x, tuple):
for i in x:
if i % 2 == 0:
return True
return False
话虽如此,它可以使用Python的生成器表达式重写为单行代码:
That being said, it can be rewritten as a one-liner using Python's generator expressions:
def isEven(x):
return any(v % 2 == 0 for v in x)
这篇关于Python:找出元组是否包含偶数的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文