簡體   English   中英

Python:ValueError:list.remove(x):x不在列表中

[英]Python: ValueError: list.remove(x): x not in list

我正在嘗試在一組字符串中找到相似的詞。 我正在使用difflib SequenceMatcher

並且一旦找到相似的單詞,為避免重復,我嘗試使用.remove(word)刪除它,但由於ValueError: list.remove(x): x not in list出現錯誤ValueError: list.remove(x): x not in list

我可以知道為什么無法從列表中刪除該元素嗎?

tags = ['python', 'tips', 'tricks', 'resources', 'flask', 'cron', 'tools', 'scrabble', 'code challenges', 'github', 'fork', 'learning', 'game', 'itertools', 'random', 'sets', 'twitter', 'news', 'python', 'podcasts', 'data science', 'challenges', 'APIs', 'conda', '3.6', 'code challenges', 'code review', 'HN', 'github', 'learning', 'max', 'generators', 'scrabble', 'refactoring', 'iterators', 'itertools', 'tricks', 'generator', 'games']

similar_tags = [] 
for word1 in tag:
    for word2 in tag:
        if word1[0] == word2[0]:
            if 0.87 < SequenceMatcher(None, word1, word2).ratio() < 1 :
                similar_tags.append((word1,word2))
                tag.remove(word1)


 print(similar_tags) # add for debugging

但我得到一個錯誤

Traceback (most recent call last):
  File "tags.py", line 71, in <module>
    similar_tags = dict(get_similarities(tags))
  File "tags.py", line 52, in get_similarities
    tag.remove(word1)
ValueError: list.remove(x): x not in list

如果你有兩句話word21word22它與匹配word1指定的約束條件下,當你從名單刪除, word21 ,沒有word1對要刪除列表中的word22

因此,您可以通過以下修改來更正它:

for word1 in tag:
    is_found = False #add this flag
    for word2 in tag:
        if word1[0] == word2[0]:
            if 0.87 < SequenceMatcher(None, word1, word2).ratio() < 1 :
                is_found = True #true here as you want to remove it after the termination of the current loop
                similar_tags.append((word1,word2))
    if is_found: #if founded this word under the specified constraint at least one time, the remove it from the list
        tag.remove(word1)

您修改要迭代的列表是一件壞事

將單詞推送到新列表,然后刪除新列表中存在的項目表單標簽列表,嘗試類似這樣的操作

similar_tags = [] 
to_be_removed = []
    for word1 in tag:
        for word2 in tag:
            if word1[0] == word2[0]:
                if 0.87 < SequenceMatcher(None, word1, word2).ratio() < 1 :
                    similar_tags.append((word1,word2))
                    to_be_removed.append(word1)

for word in to_be_removed:
    if word in tag:
        tag.remove(word)
print(similar_tags) # add for debugging

暫無
暫無

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

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