问题描述
这是我得到的。当我运行它时它不起作用。有人可以帮助指导我了解我的代码有什么问题吗?
def unique_words(text : str) ->list:
text = open(text,'r')
text_contents = text.read()
text.close()
word_list = text_contents.split()
word = open(str,'w')
unique = []
for word in word_list:
if word not in word_list:
file.append(str(word) + "\n")
unique.sort()
返回(唯一)
解决方法
使用 set() 返回唯一值并删除重复值
,Set 将保存所有唯一值。如果添加重复项,则集合将忽略它。
word_list = ['hello','hello','world','world']
unique = set()
for word in word_list:
if word not in unique:
unique.add(word)
print(unique)