【题解】Assignment 8.4 (Python Data Structures)

吐槽:没听课就做作业果然很多不会,不过善用搜索总会做出来倒是= = 记录这个题主要是查的有点多,感觉值得记一下哈0.0

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)因此如果直接 lst.append() 会导致list套list的情况发生。因此这里要用for in来做到一个word的写入lst。(https://www.cnblogs.com/pizitai/p/6398276.html

2,输出是没有查重的,所以可以用 lst = list(set(lst)) 来去重。(https://www.cnblogs.com/nyist-xsk/p/7473236.html

3,要注意 lst.sort() 是没有返回值的,所以要单独一行进行操作。(https://www.runoob.com/python/att-list-sort.html

扫描二维码关注公众号,回复: 8780781 查看本文章
发布了6 篇原创文章 · 获赞 3 · 访问量 5643

猜你喜欢

转载自blog.csdn.net/zjt1027/article/details/104071894