当我运行我的程序(anagram solver)时,我得到错误Unhashable type:list,那就是当我将wordList转换为元组但我仍然得到错误。
word.txt包含一堆像这样的单词 WORD.TXT
abruptly
abruptness
abs
abscam
这是代码:
def main():
lenWord = 4
wordList = readMatrix()
lengthWord(lenWord)
def readMatrix():
wordList = []
strFile = open("words.txt", "r")
lines = strFile.readlines()
for line in lines:
word = line.rstrip().lower()
wordList.append(word)
return tuple(wordList)
def lengthWord(lenWord):
wordList = readMatrix()
for word in wordList:
if len(word) == lenWord:
sortWord = sorted(word)
setWord = set(word)
sortDict = ({sortWord : setWord})
return sortDict
main()
答案 0 :(得分:2)
您只需将列表转回字符串(str
)
sortWord = ''.join(sorted(word))
其他合适的选择可以是tuple
或frozenset
下一行是一个错误 - 它只是一组字母
setWord = set(word)
您希望将值设为包含实际字词的集合。
例如
sortWord = ''.join(sorted(word))
if sortWord not in sortDict:
sortDict[sortWord] = set()
sortDict[sortWord].add(setWord)
答案 1 :(得分:0)