Python程序检查列表中所有值是否大于给定值
在本教程中,我们将检查列表中的所有元素是否都大于某个数字。例如,我们有一个列表 [1, 2, 3, 4, 5] 和一个数字 0。如果列表中的每个值都大于给定值,则返回True 否则返回False。
这是一个简单的程序。我们可以在不到 3 分钟的时间内编写它。请先自己尝试一下。如果你无法找到解决方案,那么请按照以下步骤编写程序。
- 初始化一个列表和任何数字
- 循环遍历列表。
If yes, return **False**
- 返回 True。
示例
## initializing the list values = [1, 2, 3, 4, 5] ## number num = 0 num_one = 1 ## function to check whether all the values of the list are greater than num or not def check(values, num): ## loop for value in values: ## if value less than num returns False if value <= num: return False ## if the following statement executes i.e., list contains values which are greater than given num return True print(check(values, num)) print(check(values, num_one))
如果你运行以上程序,
输出
True False
另一种查找方法是使用all()内置方法。all()方法如果可迭代对象中的每个元素都为True,则返回 True,否则返回False。让我们看看使用all() 方法的程序。
## initializing the list values = [1, 2, 3, 4, 5] ## number num = 0 num_one = 1 ## function to check whether all the values of the list are greater than num or not def check(values, num): ## all() method if all(value > num for value in values): return True else: return False print(check(values, num)) print(check(values, num_one))
如果你运行以上程序,
输出
True False
如果您对程序有任何疑问,请在评论区提出。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP