python - 是否可以在具有多个条件的单个 if/else 语句中找到哪个条件失败?

标签 python

很快我需要验证是否验证了 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/

相关文章:

python - 显然,Python字符串不是“天生相等”的

python - 如何从 python 应用程序确定 X 服务器/X 转发是否正在运行?

python - 如何在python中不同的两个数组上应用不同的运算符

python - Selenium 缺少 'JSESSIONID' 的 cookie 的可能原因是什么?

python - 捕获和重新抛出异常的替代方法

python - 将数据框字符串类别转换为数字

python - 如何使用 sql alchemy 进行联接查询?

Java EE updatetool 出现 Python 解码错误

python - 根据日期在 Python/Django 中过滤,忽略时间

python - 如何使用 Sympy 使用我设计的唯一变量符号求解方程