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 语句(我确实需要)时,没有任何变化。有人请吗?

除非第一行代码的输出是"ar""fr"(或不在if-elif条件下的其他内容),否则您将覆盖opt变量。考虑将"新"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')条件返回列表中存在的字符串,则上述条件至少会满足您的if-else条件。

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":

它可能会起作用(如果您显示的代码与问题相关)。

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 .它应该通过。

要通过 AND 运算符成为条件 True,所有条件都需要 True 结果。

要通过 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 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(' ')])

其计算值与预期不同。

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

最新更新