我是靠谱客的博主 真实电灯胆,最近开发中收集的这篇文章主要介绍【题解】Assignment 8.4 (Python Data Structures),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

吐槽:没听课就做题的话会发现很多不会,但是善用搜索总会解决的。顺便,我tm刚刚更新了个9.4怎么就把8.4删了??叫我重新敲一遍吗心态崩了= = 但是为了保持一下完整性,我还是重新敲了一遍(简直有病= = 以后肯定不会再憨了....

8.4 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.py4e.com/code3/romeo.txt

文件:

But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

我的程序:

fname = input("Enter file name: ")
fh = open(fname)
lst = list()    #到此为止都是题目给的
for line in fh:
    for i in line.rstrip().split(' '):
        lst.append(i)
lst = list(set(lst))
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']

我想说的:

1,str.split() 返回的是个列表(https://www.runoob.com/python/att-string-split.html),刚好可以用for...in...语句,题目上也说了要一个个word的读入,所以就会用到 list.append()(https://www.runoob.com/python/att-list-append.html),当然题目也提示了要用这个append。

2,观察文件发现还有去重要做,所以用 lst = list(set(lst)) 集合的互异性来实现去重,这里有方法(https://blog.csdn.net/harry_128/article/details/80536305)。

3,list.sort() 没有返回值,所以要单独写一行,一开始不知道写成 print(lst.sort()) 了,感觉不注意返回值也太憨了以后要注意(https://www.runoob.com/python/att-list-sort.html)。

4,一开始不理解 for line in fh: 为什么可以读取每一行,查资料后发现 readlines() 返回值是列表刚好可以实现(https://www.runoob.com/python/file-readlines.html),感觉应该是fh自动调用了fh.readlines(),不过也没啥证据就是推测,以后有证据再补充咯。

最后

以上就是真实电灯胆为你收集整理的【题解】Assignment 8.4 (Python Data Structures)的全部内容,希望文章能够帮你解决【题解】Assignment 8.4 (Python Data Structures)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部