Python如何在一个if语句中检查变量是否存在及其长度?

发布于 2024-12-05 18:17:04 字数 283 浏览 0 评论 0原文

这是我的情况:

if var:
    if len(var) == 5:
        do something...
else:
    do the same thing...

为了避免重复同一段代码,我想将这 2 个 if 条件合并为一个。但如果 var 是 None,我无法检查它的长度......知道吗? 我想要这样的东西:

if var and len(var) == 5:
    do something...

Here's my situation:

if var:
    if len(var) == 5:
        do something...
else:
    do the same thing...

To avoid repeating the same piece of code, I would like to combine those 2 if conditions, in one. But if var is None, I can't check its length... Any idea?
I would like something like this:

if var and len(var) == 5:
    do something...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌逼全场 2024-12-12 18:17:04

你尝试过吗?它有效:

if var and len(var) == 5:
    ....

如果 LHS 为 false,则 and 运算符不会计算 RHS。试试这个:

>>> False and 1/0
False
>>> True and 1/0
ZeroDivisionError: division by zero

Did you try that? It works:

if var and len(var) == 5:
    ....

The and operator doesn't evaluate the RHS if the LHS is false. Try this:

>>> False and 1/0
False
>>> True and 1/0
ZeroDivisionError: division by zero
纵山崖 2024-12-12 18:17:04

您在问题中编写的代码在两种情况下执行语句:

  • var 计算结果为 true,长度为 5
  • var 计算结果为 false(例如,它是 < code>None 或 False

您可以将它们组合成一个条件,如下所示:

if not var or len(var) == 5:
    ...

其他一些答案建议的条件,var and len(var) == 5,仅评估为True 在第一种情况下,而不是在第二种情况下。不过,我要说的是,您选择的两种情况是一种不寻常的组合。您确定您不打算仅在变量具有非假值长度为 5 时才执行语句吗?

此外,正如 6502 在评论中所写,函数正是针对这种情况,即制作可重用的代码块。所以另一个简单的解决方案是

 def f():
     ....
 if var:
     if var.length == 5:
         f()
 else:
     f()

The code as you've written it in the question executes the statements in two cases:

  • var evaluates to true and has a length of 5
  • var evaluates to false (e.g. it's None or False)

You can combine those into one conditional as follows:

if not var or len(var) == 5:
    ...

The conditional that some other answers are suggesting, var and len(var) == 5, only evaluates to True in the first case, not the second. I will say, though, that the two cases you've chosen are kind of an unusual combination. Are you sure you didn't intend to execute the statements only if the variable has a non-false value and has a length of 5?

Additionally, as 6502 wrote in a comment, functions are intended for exactly this case, namely making reusable code blocks. So another easy solution would be

 def f():
     ....
 if var:
     if var.length == 5:
         f()
 else:
     f()
梦中的蝴蝶 2024-12-12 18:17:04

好吧,例外在这里似乎完全没问题。

try:
    if len(var) == 5:
        do_something()
except TypeError:
    pass

您说 var 可以为 null,因此会抛出 TypeError 异常。然而,如果事实上 var 可能根本不存在,那么您应该捕获 NameError 异常。

Well, exceptions seem to be perfectly fine here.

try:
    if len(var) == 5:
        do_something()
except TypeError:
    pass

You're saying that var can be null, therefore a TypeError exception would be thrown. If, however, in fact var can be non-existant at all, you should catch for NameError exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文