【问题标题】:Checking if string is in a list of strings using loop使用循环检查字符串是否在字符串列表中
【发布时间】:2021-04-18 11:09:34
【问题描述】:

我有一个函数,它使用 for 和 while 循环检查给定字符串是否在字符串列表中。我不应该使用“in”运算符。这是我使用 for 循环的代码:

def word_in_list(words, word):
    for strings in words:
        if len(words) > 0 and strings == word:
            return True
        else:
            return False

但是,除非单个字符串是列表的第一个元素,否则它不会返回 True。如果列表为空,则列表应返回 False。以及如何使用 while 循环(并且不使用 'in' 运算符)解决相同的问题?

【问题讨论】:

  • 所以你不应该在 for 循环中返回 false。将语句 return false 放在 for 循环之后。逻辑是,如果您找到该单词,则返回 true。一旦for循环完成而没有找到它,返回false。

标签: python string for-loop while-loop


【解决方案1】:

您的 else 块在没有完成完整列表上的迭代的情况下启动。

def word_in_list(list_of_words, word_to_search):
    found = False
    for word in list_of_words:
        if word == word_to_search:
            found = True
            break # breaks iff the word is found
    return found 

您坚持不使用“in”运算符的任何特殊原因? 另外,请注意您粘贴的代码中的缩进。

【讨论】:

  • 谢谢!!这个练习完全是关于循环的,否则会更容易哈哈
【解决方案2】:

只需使用此代码

def word_in_list(words, word):
    if word in words:
       return True
    else
       return False

【讨论】:

  • in 根据 OP 的条件不允许使用。而你用的是in,直接做return word in words就够了。
  • 另一方面,问题指出,应该使用 for 循环,并且不能在没有 `in` 的情况下编写 for 循环。
【解决方案3】:

当您发现一个不匹配时不要返回False,当您检查完所有可能性但没有找到任何匹配时返回False

def word_in_list(words, word):
    for strings in words:
        if strings == word:
            return True
    return False

另外,不需要每次都检查list的长度,如果为零,则根本不运行循环,直接返回False

【讨论】:

    【解决方案4】:

    由于 else 语句,您的代码是错误的。您的函数必须仅在检查整个列表后才返回 False,而不仅仅是第一个元素。每当一个函数到达“返回”指令时,它就会停止,所以它只检查第一个。这是正确的解决方案:

    def word_in_list(words, word):
        i = 0
        while i < len(words):
            if words[i] == word:
                return True
            i += 1
        return False
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 2023-03-14
      • 1970-01-01
      • 2013-04-29
      • 2015-05-05
      • 1970-01-01
      • 2017-09-06
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多