📜  Python|测试虚假列表

📅  最后修改于: 2022-05-13 01:54:42.625000             🧑  作者: Mango

Python|测试虚假列表

有时,我们需要检查一个列表是否完全正确或错误,这些情况在开发阶段之后的测试目的中更常见。因此,了解这一切是必要且有用的。让我们讨论可以执行此操作的某些方式。

方法#1:朴素的方法
在朴素的方法中,我们只是从 beg 到列表末尾运行一个循环,并手动检查每个值。这是执行此特定任务的最基本方法。

# Python3 code to demonstrate 
# to check for False list 
# using naive method
  
# initializing list  
test_list = [False, False, False, False]
  
# printing original list
print ("The original list is : " + str(test_list))
  
flag = 0
  
# using naive method 
# to check for False list 
for i in test_list :
    if i == True :
        flag = 1
        break
  
# printing result
print ("Is List completely false ? : " +  str(bool(not flag)))
输出:
The original list is : [False, False, False, False]
Is List completely false ? : True


方法 #2:使用all()
此函数测试每个值是否为 False,如果是,则返回布尔值 True,否则返回 false。列表迭代是使用列表推导完成的。

# Python3 code to demonstrate 
# to check for False list 
# using all()
  
# initializing list  
test_list = [False, False, False, False]
  
# printing original list
print ("The original list is : " + str(test_list))
  
flag = 0
  
# using all()
# to check for False list 
res = all(not i for i in test_list)
  
# printing result
print ("Is List completely false ? : " +  str(res))
输出:
The original list is : [False, False, False, False]
Is List completely false ? : True


方法 #3:使用any()
此函数测试任何一个 True 值,如果找到返回 True,否则返回 False 值。该函数的否定被用作结果。

# Python3 code to demonstrate 
# to check for False list 
# using any()
  
# initializing list  
test_list = [False, False, False, False]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# using any()
# to check for False list 
res = not any(test_list)
  
# printing result
print ("Is List completely false ? : " +  str(res))
输出:
The original list is : [False, False, False, False]
Is List completely false ? : True