List_排序
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
代码:
fhand = input("Enter file name:")
ap_words_line = list()
no_rep_result = []
fh = open(fhand)
for words in fh: #将每行读取的单词以字符串形式存储起来了(因为我不知道怎么让他一个一个单词读出来)
words_line = words.split()
ap_words_line.append(words_line)
new_line = ap_words_line[0] + ap_words_line[1] + ap_words_line[2] + ap_words_line[3] #假如我不知道长度的话怎么办呢?
for index in new_line:
if index not in no_rep_result:
no_rep_result.append(index)
no_rep_result.sort()
print(no_rep_result)
#当自己不知道具体输出什么内容时候,可以再循环中假如print随时打印出来
#这个题目如果用了set,就好难排序了,会提示这个set没有sort
#题目来源于cousera课程练习
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
浙公网安备 33010602011771号