我是靠谱客的博主 疯狂小丸子,这篇文章主要介绍Python.Lists,现在分享给大家,希望可以做个参考。

Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.

You can download the sample data at http://www.pythonlearn.com/code/romeo.txt 


fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
     for word in line.split():
          if word not in lst:
               lst.append(word)
               lst.sort()
print lst

输出:

Enter file name: romeo.txt
['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']


最后

以上就是疯狂小丸子最近收集整理的关于Python.Lists的全部内容,更多相关Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(123)

评论列表共有 0 条评论

立即
投稿
返回
顶部