循环大量单词时出现奇怪的行为

时间:2019-06-28 16:47:13

标签: python

  1. #validCandidateList += word保持注释时,程序运行正常。取消注释该行后,程序将一遍又一遍打印出重复的行。

  2. 2。如您所见sorted(set(eWord))已排序,因此 例如,如果我输入“ dog”或“ good”,它将创建相同的排序列表 字母-['d', 'g', 'o'],但程序不会打印 输入为good时,将单词dog删除,即使您可以 通过输入两个词来确认字典中是否存在这两个词 在单个程序中,用空格隔开,或输入以下内容之一 对不起,我只需要对单词应用.lowercase()即可。字典也包含一些大写字母。

    请帮助。

import os

cwd = os.path.dirname(os.path.abspath(__file__))
fname = "\\dictionary.txt"
file = open(cwd + fname, "r")
readFile = file.read()
dictionary = readFile.split() #list type variable with more than 400 000 words.

input = input("Input your list of words, separated by spaces: ")
inputList = input.split()

validCandidateList = inputList

for eWord in dictionary: 
    for word in inputList:
        if sorted(set(eWord)) == sorted(set(word)):
            print(word, ": ",eWord)
            #validCandidateList += word

print(validCandidateList)

3 个答案:

答案 0 :(得分:2)

我找到了!

您的行在这里:

validCandidateList = inputList

不会像您期望的那样将inputList的内容复制到名为validCandidateList的新变量中,它只是链接两个变量,因此当您在循环内更改validCandidateList时,它也会同时更改inputList,您正试图循环。更改您要遍历的列表会在Python中引起大问题(请勿这样做)。因此,要解决此问题,您需要像这样将inputList的内容实际复制到validCandidateList中:

validCandidateList = inputList[:]

或者,如果您使用的是Python 3,则可以使用copy()函数

validCandidateList = inputList.copy()

对于您正在做的事情来说,这看起来更明显,但两者都很好:)

答案 1 :(得分:0)

关于您提到的第一个问题:

这些行是它的起源:

inputList = input.split()
validCandidateList = inputList

这是参考分配,这意味着只要validCandidateList发生变化,inputList也会发生变化。

您在inputList上循环,并在循环内更改validCandidateList,这基本上扩展了循环,并看到了重复的输出。

示例:

x = [1,2,3]
y = x
y.append(4)
print(x)
# output => [1,2,3,4]

为了纠正该行为,可以使用copy运算符:

validCandidateList = inputList.copy()

这将对您的列表进行浅表复制并提供新的引用。

有关copy工作原理的更多信息,请参见官方文档here

希望这会有所帮助。

答案 2 :(得分:0)

我认为您需要使用一个空列表初始化列表,而不是添加到现有列表中,请尝试以下操作:

validCandidateList = []

然后再

validCandidateList.append(word)

希望这会有所帮助!