繁体   English   中英

如何检查python中的变量是否相等

[英]how do you check if variable is equal in python

我有一个线阵列,位置5的值可以是以下两个值之一:

"Tablespace Free Space (MB)", "Tablespace Space Used (%)"

如果line[5]是其中的任何一个,我需要做一些额外的工作。

我已经试过了:

if (line[5] in ("Tablespace Space Used (%)")|("Tablespace Free Space (MB)"))

    # some other code here

我不断收到此错误:

    if (line[5] in ("Tablespace Space Used (%)"|"Tablespace Free Space (MB)"))
                                                                             ^
SyntaxError: invalid syntax

您在if语句末尾缺少:

但是,您也在测试中使用了无效的语法。 它将导致运行时错误( TypeError: unsupported operand type(s) for |: 'str' and 'str' )。 您要创建一个元组或一组要测试的字符串,而不要使用|

if line[5] in ("Tablespace Space Used (%)", "Tablespace Free Space (MB)"):

要么

if line[5] in {"Tablespace Space Used (%)", "Tablespace Free Space (MB)"}:

后者在技术上效率更高,除非您使用的是Python 2,而该Python 2中的集合未按照元组在任一语言版本中的方式优化为常数。 使用{...}创建集合需要Python 2.7或更高版本。

您使用==检查相等性

4 == 2*2
True

要使用if语句,请在行末添加“:”

if line[5] in {'Tablespace Space Used (%)', 'Tablespace Free Space (MB)'}:
   do x

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM