【问题标题】:Python: ValueError: list.remove(x): x not in listPython:ValueError:list.remove(x):x不在列表中
【发布时间】:2018-10-07 08:02:45
【问题描述】:

我试图在一组字符串中找到相似的单词。我正在使用来自difflibSequenceMatcher

一旦找到类似的单词,为了避免重复,我尝试使用.remove(word) 将其删除,但出现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

【问题讨论】:

标签: python python-3.x list


【解决方案1】:

如果您有两个词 word21word22 在指定的约束下与 word1 匹配,当您从 word21 的列表中删除时,列表中没有 word1word22 删除。

因此,您可以通过以下修改来纠正它:

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)

【讨论】:

  • 你能添加一个例子吗?
  • @rɑːdʒɑ 我的荣幸
【解决方案2】:

你修改了一个你正在迭代的列表,这是一件坏事

将单词推送到新列表然后删除新列表中存在的项目表单标签列表尝试类似这样的操作

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2022-01-12
    • 1970-01-01
    • 2018-07-05
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多