简体   繁体   English

如果列表中有任何偶数,如何检查python

[英]how to check in python if there is any even number in list

I am a newbie who just start learning python.我是一个刚开始学习python的新手。 here is my list:这是我的清单:

list1 = [3,105,97,17,68241,5,3,8,]

how I will check if there is any even number in my list我将如何检查我的列表中是否有偶数

Try and identify what makes a number even.尝试并确定是什么使数字成为偶数。 In your head, what could you do to the number to prove it is even?在你的脑海中,你能对这个数字做些什么来证明它是偶数? You divide it by 2 and see if the remainder is 0. In programming, we use the modulo operator (%) to get the remainder of an equation.您将其除以 2 并查看余数是否为 0。在编程中,我们使用模运算符 (%) 来获得等式的余数。

Try and think of a way that you can iterate over the items in your list and see if they are even using the above method.尝试并想出一种方法,您可以迭代列表中的项目,看看它们是否甚至使用上述方法。

You can use the Python builtin function which name is any().您可以使用名称为 any() 的 Python 内置函数。 here is my code which will check if your list have any even number.这是我的代码,它将检查您的列表是否有任何偶数。 You will get true value if there is any even number in your list otherwise it will return false.如果您的列表中有任何偶数,您将获得真值,否则将返回假。

list1 = [3,105,97,17,68241,5,3,8,]
print(any(num%2 == 0 for num in list1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM