【问题标题】:How to compare a string with a list in python如何将字符串与python中的列表进行比较
【发布时间】:2020-12-02 18:20:32
【问题描述】:

我想比较一个字符串和一个列表,但是我的代码不起作用

def compare(typeOfColors):
   introduceC = input("Introduce a color")
   while(introduceC.lower() != typeOfColors)
       print("Error")
colors = ["white", "black"] 
compare(colors)

【问题讨论】:

标签: python string list function compare


【解决方案1】:

要知道字符串是否在 typeOfColors 中,只需使用 in

注意introduceC 在你的循环中没有改变,所以如果introduceC.lower() != typeOfColors为假你循环没有结束

循环直到输入是你可以做的列表的一部分

def compare(typeOfColors):
   while (not input("Introduce a color: ").lower() in typeOfColors):
       print("Error")

compare(["white", "black"])

例子

Python 3.7.3 (default, Jul 25 2020, 13:03:44) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def compare(typeOfColors):
...    while (not input("Introduce a color: ").lower() in typeOfColors):
...        print("Error")
... 
>>> compare(["white", "black"])
Introduce a color: blue
Error
Introduce a color: red
Error
Introduce a color: bLack
>>> 

【讨论】:

    【解决方案2】:

    使用in 关键字来测试数组是否包含值。

    def compare(typeOfColors):
       introduceC = input("Introduce a color")
       while introduceC.lower() not in typeOfColors:
           print("Error")
    colors = ["white", "black"] 
    compare(colors)
    

    但这会引入一个新错误,即无限循环,您可以这样解决:

    def compare(typeOfColors):
        introduceC = input("Introduce a color: ")
        if introduceC.lower() not in typeOfColors:
           print("Error")
           return compare(typeOfColors)
    
        print('Exists!')
        return introduceC
    
    colors = ["white", "black"] 
    compare(colors)
    

    给予:

    Introduce a color: red
    Error
    Introduce a color: blue
    Error
    Introduce a color: whitE   
    Exists!
    

    如果用户输入的内容不在可接受的值中,函数会调用自身,从而有效地重新启动。那就是递归。

    【讨论】:

    • introduceC 永不改变 => 如果测试为假,则循环不结束
    • @bruno,我确实提到了很多,无论如何我现在给出了一个更完整的解决方案。
    • 谢谢,但如果它不在列表中,我希望程序再次询问颜色
    • @BRT88 又问了,试试看!
    【解决方案3】:

    尝试遍历列表的每个元素。 然后将每个元素与颜色进行比较。

    如果您需要更多帮助,我会尽力帮助您。

    【讨论】:

    • 列表中不需要顶部循环,in 会为你做这些
    • 但是如果我做一个 for 循环,也许正确的颜色是最后一个,但我会收到其他人以前的“错误”消息
    • 那我真的不明白你想要什么。
    猜你喜欢
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    相关资源
    最近更新 更多