Python:Error 在尝试按字母顺序对集合进行排序时

Python:Error while trying to sort a set alphabetically

我正在尝试按字母顺序对集合进行排序。这是我正在使用的语句:

for sentence in corpus:
    allword=allword.union(set(sentence.split(' ')))
    allword=sorted(allword)

我收到错误“'list' 对象没有属性 'union'”。但是如果我删除要排序的代码,我就不会收到此错误。也就是说,代码在这种情况下完全有效:

allword=allword.union(set(sentence.split(' ')))

但是当我添加第二行时出现错误。 有人可以帮我理解为什么会出现这种奇怪的行为吗?我哪里错了?提前致谢

如评论中所述,您在循环中调用这些命令:一开始设置了 allword,然后 sorted() 将 allword 更改为列表。第二次迭代你会得到错误 - 列表没有 union() 方法。

解决办法是把sorted()从循环中去掉,只在最后做一次:

corpus = [
    'I am trying to sort a set alphabetically',
    'This is the statement I am using'
]


allword = set()

for sentence in corpus:
    allword=allword.union(sentence.split(' '))

print( sorted(allword) )

打印:

['I', 'This', 'a', 'alphabetically', 'am', 'is', 'set', 'sort', 'statement', 'the', 'to', 'trying', 'using']