【发布时间】:2018-12-19 06:29:22
【问题描述】:
对于 Python 3 中的作业,我需要创建一个执行以下操作的程序:
- 打开用户选择的文本文件
- 将文本文件中的所有单词附加到列表中
- 对列表中的单词进行排序
- 打印与所需结果匹配的排序列表
我拥有的代码将对列表进行排序,但不会将列表重复数据删除到所需的结果。文本文件是罗密欧与朱丽叶的独白的前四行。
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
lst.append(word)
lst.sort()
print(lst)
想要的结果是:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
但是使用我的代码,我得到了重复的单词:
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun', 'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']
如何删除列表中的重复数据?
【问题讨论】:
-
一定是列表?你不能用Sets吗?
-
print(list(set(lst)))将产生正确的结果。
标签: python python-3.x