【问题标题】:split a string into a list and use in If Statement将字符串拆分为列表并在 If 语句中使用
【发布时间】:2016-05-24 13:21:23
【问题描述】:

我对这段代码有疑问。它将一个字符串拆分为一个列表并对其进行解析。当我识别列表中的一个单词时,我想做一些事情。我查看了IF 语句,尽管它具有逻辑意义,但无论输入的句子如何,代码都只会产生语句“屏幕问题建议”。我对为什么我不能在条件语句中使用 current_word 感到有些困惑。这有什么明显的问题吗?

text=str(input("enter your problem"))
words = text.split()

for current_word in words:
    print(current_word)
    if current_word=="screen":
        print("screen problem advice")
    elif current_word=="power":
        print("power_problem advice ")     
    elif current_word=="wifi":
        print("connection_problems advice")

任何建议将不胜感激。

【问题讨论】:

  • 这对我来说很好。请显示一个您认为不正确的示例输入-输出对。

标签: string list python-3.x if-statement


【解决方案1】:

如果我在我的机器上运行你的代码,它会正常工作。

if elif elif elif else 的一些简短模式是使用一些dict() 并使用.get() 方法进行查找。

像这样的一些代码......

if word == "one":
    variable = "11111"
elif word == "two":
    variable = "22222"
elif word == "three":
    variable = "33333"
else:
    variable = "00000"

...可以写成更短的形式:

variable = dict(
    one="11111",
    two="22222",
    three="33333"
).get(word, "00000")

回到你的问题。这是一些示例。 我创建了一个detect 函数,它产生所有检测到的建议。 在main 函数中,建议只是打印出来。

请注意ISSUES.get(word.lower())里面的.lower(),所以它可以捕捉到“wifi”、“Wifi”、“WiFi”...的所有变体。

def detect(message):
    ISSUES = dict(
        wifi="network problem_advice",
        power="power problem_advice",
        screen="screen problem_advice"
    )

    for word in message.split():
        issue = ISSUES.get(word.lower())
        if issue:
            yield issue


def main(message):
    [print(issue) for issue in detect(message)]

if __name__ == '__main__':
    main("The screen is very big!")
    main("My power supply is working fine, thanks!")
    main("Wifi reception is very good today!")

此外,我特意选择了一些奇怪的例子来指出你尝试解决问题的一些基本问题。

简单的字符串匹配是不够的,因为在这种情况下会产生误报。 尝试考虑其他方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 2019-04-16
    • 2014-06-18
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多