python if ... elif总是不工作

nis*_*ish 0 python

很抱歉发布这样一个天真的问题,但我只是无法解决这个问题.我写了以下条件语句:

if taxon == "Bracelets":
    catId = "178785"
elif taxon == "Kids Earrings" or "Earrings":
    catId = "177591"
elif taxon == "Mangalsutras":
    catId = "177595"
elif taxon == "Necklaces" or "Necklace Sets":
    catId = "177597"
elif taxon == "Kids Pendants" or "Pendants":
    catId = "177592"
elif taxon == "Pendant Sets":
    catId = "177593"
elif taxon == "Anklets":
    catId = "178788"
elif taxon == "Toe Rings":
    catId = "178787"
elif taxon == "Rings":
    catId = "177590"
else:
    print "no match\n"
Run Code Online (Sandbox Code Playgroud)

但无论分类单位的价值是什么,它总是落在第二个条件下,即

elif taxon == "Kids Earrings" or "Earrings":
    catId = "177591"
Run Code Online (Sandbox Code Playgroud)

因此,catId的价值仍然存在177591.

YXD*_*YXD 13

这应该是

elif taxon == "Kids Earrings" or taxon == "Earrings":
Run Code Online (Sandbox Code Playgroud)

您的原始代码测试的是真值,"Earrings"而不是是否taxon具有该值"Earrings"

>>> bool("Earrings")
True
Run Code Online (Sandbox Code Playgroud)

更好的结构方法是使用字典:

id_map = {}
id_map["Bracelets"] = "178785"
id_map["Earrings"] = "177591"
id_map["Kids Earrings"] = "177591"
# etc
Run Code Online (Sandbox Code Playgroud)

然后你可以做

id_map[taxon]
Run Code Online (Sandbox Code Playgroud)

这也更适合存储在配置文件或数据库中,以避免对Python代码中的值进行硬编码.


wim*_*wim 7

其他人已经给出了你的问题的语法答案.

我的答案是改变这个丑陋的代码以使用字典查找.例如:

taxes = {"Bracelets": 178785, "Necklaces": 177597, "Necklace Sets": 177597}
#etc
Run Code Online (Sandbox Code Playgroud)

然后你用

catId = taxes[taxon]
Run Code Online (Sandbox Code Playgroud)