0

正在尝试从书籍 think python 中进行此练习。编写一个程序,从文件中读取一个单词列表(参见第 9.1 节)并打印出所有属于 anagrams 的单词集。

我的策略是获取文件,对每个单词进行排序并存储在字符串列表中(称为 listy)。然后,我将再次查看原始单词列表并与 listy 进行比较。如果相同,则将已排序的单词存储为键,将原始文件中的未排序单词存储为字典中的值。然后只需打印出每个键下的所有值。它们应该是字谜。

我创建的第一个函数是生成列表。已经分解了代码并检查了它,看起来很好。但是,当我编译并运行它时,python 就像遇到无限循环一样挂起。谁能告诉我为什么会这样?

def newlist():
    fin = open('words.txt')
    listy = []
    for word in fin:
        n1 = word.strip()
        n2 = sorted(n1)
        red = ''.join(n2) 
        if red not in listy:
            listy.append(red)

    return listy

newlist()
4

1 回答 1

0

使用 aset检查单词是否已被预处理:

def newlist():
    with open('words.txt') as fin:
        listy = set()
        for word in fin:
            n1 = word.strip()
            n2 = sorted(n1)
            red = ''.join(n2)
            listy.add(red)
    return listy

newlist()

你甚至可以把它写成:

def newlist():
    with open('words.txt') as fin:
        return set(''.join(sorted(word.strip())) for word in fin)

newlist()
于 2013-09-26T09:07:53.963 回答