【问题标题】:Unable to eliminate words in a list using a for and while loop in Python [duplicate]无法使用 Python 中的 for 和 while 循环消除列表中的单词 [重复]
【发布时间】:2020-08-28 09:00:32
【问题描述】:

我试图寻找所有可以通过重新排列单词“PLANETS”来组成的 7 个字母的单词,作为练习(我使用了从这里下载的 sowpods 库:http://norvig.com/ngrams/sowpods.txt)。

这是代码:

file_name = 'sowpods.txt'
a = open(file_name,'r')
b = a.read()
c = b.split('\n')
d = []

for corr in c:
    if len(corr) == 7:
        d.append(corr)
        
for corr in d:
    m = 0
    while m < 7:
        if (corr[m] == 'P' or corr[m] == 'L' or corr[m] == 'A' or corr[m] == 'N' or corr[m] == 'E' or corr[m] == 'T' or corr[m] == 'S'):
            pass
        else:
            d.remove(corr)
            break
        m += 1
print(d)

该程序运行时没有任何错误消息,但它并没有删除我期望它删除的许多单词,即使它删除了其他类似的单词,例如,它删除了单词“ZORILLA”但没有删除“ZORILLE”。我不确定它为什么这样做。有人可以解释一下,并建议对代码进行一些更改吗?

【问题讨论】:

    标签: python python-3.x for-loop while-loop


    【解决方案1】:

    从您正在迭代的列表中删除一个项目会混淆迭代。只需清空该项目,或反向迭代列表。

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      相关资源
      最近更新 更多