在本教程中,我们将检查列表中的所有元素是否都大于数字。例如,我们有一个列表[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()内置方法。所有()方法返回true,如果从每一个元素迭代是真,否则返回假。让我们看一下使用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
如果您对该程序有任何疑问,请在评论部分中提及它们。