python - 没有项目从列表中删除

标签 python string list python-3.x for-loop

我使用的是 Python 3.5,我的代码是

words = open("wordlist.txt").readlines()
words = [k[:-2] for k in words]
noletters = ["b", "d", "f", "g", "h", "i", "j", "k", "l", "p", "q", "t", "y"]
for n in words:
    for i in n:
        if i in noletters:
            words.remove(n)
            break
words.sort()
words.sort(key = len)
print(words)

这里,wordlist.txtreally, really, really long list of words 。首先,我从列表中的每个项目中删除一些不必要的字符,然后我最终得到一个列表,其中每个项目都是一个单词 - 类似于 'hello'yugoslavia 。到目前为止这有效。

然后,我创建了一个字母列表,我不想让这些字母出现在我从程序中得到的任何单词中。然后,对于列表中的每个项目,我检查单词中的每个字母,如果该字母在列表中,我从列表中删除该单词并打破检查字母的内部循环(这可以防止系统尝试删除已删除的内容)。然后,我按字母顺序和单词长度对列表进行排序,然后打印列表。

问题:

  1. 循环没有从列表中删除任何内容,我不知道为什么。它肯定会进入循环 - 我添加了一些打印语句(在 words.remove(n) 行之后,以便在删除某些内容时进行打印,也在 break 之后线,看看它何时移动到一个新单词)。
  2. 按字符串长度排序的语句还添加了一堆从未出现在单词列表中的内容 - 例如,'o' 不在列表中,但它被添加了,以及几个空白字符串 ('') 等等 - 它看起来像是字母表中每个字母的所有可能组合。

最佳答案

来自文档 for statement .

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy.

如果我没有误解你的意思,也许你可以尝试做一个浅拷贝:

for n in words[:]:
    for i in n:
        if i in noletters:
            words.remove(n)
            break

或者也许您可以使用此列表理解:

words=[n for n in words if  not any([i in noletters for i in n])]

希望这有帮助。

关于python - 没有项目从列表中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43289208/

相关文章:

java - 逐行比较文本文件与动态变量

java - 如何将 List<?> 与 HtmlUnit 方法一起使用?

python - 如何在 Python 中使用空分隔符拆分字符串

javascript - Python WebSocket 不工作

python - 具有相同参数的函数的全局变量与参数

python - 如何检查日期时间是否在中午之前

java - 拆分全名

python - 通过括号将 "Nested"字符串拆分为嵌套列表

c# - 在 List<T> 中查找 IEnumerable<T> 时,GetGenericTypeDefinition 返回 false

python - 使用 tkinter 在单个窗口中将多个框架与小部件组合在一起