Python 与或语句

Python AND OR statements

我正在用 Python 解析文本,我有这个最终代码来写句子,但效果不佳:

        opt = child.get('desc')
        extent = child.get('extent')
        if opt == 'es':
            opt = "ESP:"
        elif opt == "la":
            opt = "LAT:"
        elif opt == "en":
            opt = "ENG:"
if opt in ["es","la","en","ar","fr"] and extent == "begin":
    print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])

它只适用于 OR 语句,但是当我添加 AND 语句(我确实需要)时,没有任何变化。有人要吗?

AND

要通过 AND 运算符 成为条件真,需要 所有条件 的结果 .

要通过 OR 运算符 成为条件 True,需要 True 来自任何 一个条件 的结果].

例如

In [1]: True and True
Out[1]: True

In [2]: True and False
Out[2]: False

In [3]: True or False
Out[3]: True

在您的代码中,打印以下语句:

print "Debug 1: opt value", opt
print "Debug 2: extent value", extent

为什么还要用同一个变量名??

如果 opt 的值是 es 那么如果条件 if opt == 'es':True 并且 opt 变量再次分配给值 ESP: . 在你最后的 if 语句中你检查 opt in ["es","la","en","ar","fr"] ,所以它总是 False

    opt = child.get('desc')
#   ^^
    extent = child.get('extent')
    if opt == 'es':
        opt = "ESP:"
    #   ^^
    elif opt == "la":
        opt = "LAT:"
    elif opt == "en":

您在 if 语句的第一个条件中的选择列表有问题。

如果opt恰好是es,例如,那么

if opt == 'es':
    opt = "ESP:"

会将其更改为 ESP:

if opt in ["es","la","en","ar","fr"] and extent == "begin":

永远不会是 True(当您使用 and 而不是 or 时)。

如果您将该行更改为

if opt in ["ESP:","LAT:","ENG:","ar","fr"] and extent == "begin":

它可能有效(如果您显示的代码与问题相关)。

除非第一行代码的输出是 "ar""fr"(或其他不在 if-elif 条件中的东西),否则您将覆盖 opt 变量。考虑将 'new' opt 重命名为其他名称,如下所示:

opt = child.get('desc')

extent = child.get('extent')

if opt == 'es':
    opt2 = "ESP:"
elif opt == "la":
    opt2 = "LAT:"
elif opt == "en":
    opt2 = "ENG:"

# Check variable values
print "opt: ", opt
print "opt2: ", opt2

if opt in ["es","la","en","ar","fr"] and extent == "begin":
    print time, opt2+(" " + opt2).join([c.encode('latin-1') for c in child.tail.split(' ')])

我不确定你到底想从代码中实现什么,但如果原始 child.get('desc') 条件 returns 字符串,上面至少会满足你的 if-else 条件存在于列表中。

opt 是其中之一时:"es", "la", "en"
然后 opt 的值被改变了,这个:
if opt in ["es","la","en","ar","fr"] and extent == "begin":
不会通过,因为opt错了

我猜 extent 等于 "begin",所以如果你把 and 换成 or 它就会通过,因为其中一个陈述是正确的。尝试删除这个大 if/elif/elif 并尝试使用 and 再次 运行 它。它应该通过。

这是一个运算符优先级问题。您希望代码按以下方式工作:

if (opt in ["es","la","en","ar","fr"]) and (extent == "begin"):
    print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])

但它的工作原理是

if opt in (["es","la","en","ar","fr"] and extent == "begin"):
    print time, opt+(" " + opt).join([c.encode('latin-1') for c in child.tail.split(' ')])

其计算结果与您预期的不同。

尝试第一个代码段中的括号。