很快我需要验证是否验证了 3 个条件,如果没有验证失败的条件,则执行一些操作。我知道我可以使用多个 if/else 语句遍历 3 个条件,但我想知道是否有更简单、更简洁的方法来做到这一点。
以更通用的方式:
if condition1 and condition2 and condition3: pass
else: print which condition has failed
一个应用案例:
if file_exist("1.txt") and file_exist("2.txt") and file_exist("3.txt"):
pass
else:
#find which condition has failed
#for file of the failed condition
create_file(...)
我不是要解决上面的例子!我的问题是关于在单个 if/else 语句的一系列条件中找出哪个条件未得到验证的方法!
问候
最佳答案
I know I can iterate through the 3 files with multiple if/else statements
每当您在编程问题中注意到这样的重复时,这就是您可以使用循环的一个很好的迹象:
for filename in ("1.txt", "2.txt", "3.txt"):
if not file_exist(filename):
create_file(...)
您还可以使用列表理解:
[create_file( filename ) for filename in ("1.txt", "2.txt", "3.txt") if not file_exist(filename)]
这更接近于您用英语阅读它的方式,但有些人会对此不以为然,因为您使用的是列表理解来产生副作用,而不是实际创建一个列表 .
关于python - 是否可以在具有多个条件的单个 if/else 语句中找到哪个条件失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689678/