Python:ValueError:list.remove(x):x不在列表中 [英] Python: ValueError: list.remove(x): x not in list

查看:2899
本文介绍了Python:ValueError:list.remove(x):x不在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一组字符串中找到相似的单词.我正在使用difflib中的SequenceMatcher.

I am trying to find similar words in a group of strings. I am using SequenceMatcher from difflib.

并且一旦找到类似的单词,为避免重复,我尝试使用.remove(word)删除它,但由于ValueError: list.remove(x): x not in list出现错误.

And once a similar word found, to avoid duplication I am trying to remove it with .remove(word) but getting error as ValueError: list.remove(x): x not in list.

我可以知道为什么无法从列表中删除该元素吗?

May I know why I am unable to remove that element from 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,列表中没有要为word22删除的word1.

If you have two words word21 and word22 which matches with the word1 under the specified constraints, as you remove from the list for the word21, there is no word1 in the list to be removed for word22.

因此,您可以通过以下修改对其进行纠正:

Hence, you can correct it by the following modification:

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)

这篇关于Python:ValueError:list.remove(x):x不在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆