簡體   English   中英

使用循環檢查字符串是否在字符串列表中

[英]Checking if string is in a list of strings using loop

我有一個 function 使用 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'運算符)解決同樣的問題?

由於 else 語句,您的代碼是錯誤的。 您的 function 必須僅在檢查整個列表后返回 False,而不僅僅是第一個元素。 每當 function 到達“返回”指令時,它就會停止,所以它只檢查第一個。 這是正確的解決方案:

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

當你發現一個不匹配時不要返回False ,當你檢查完所有可能性並且沒有找到任何匹配時返回False

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

另外,不需要每次都檢查 list 的長度,如果它為零,則根本不運行循環並直接返回False

只需使用此代碼

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

您的 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”運算符的任何特殊原因? 另外,請注意您粘貼的代碼中的縮進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM