【问题标题】:Usage of split, rstrip, append in listssplit、rstrip、append 在列表中的用法
【发布时间】:2017-07-02 04:11:25
【问题描述】:

这周的作业是关于列表的问题,我无法摆脱列表符号。

打开文件 romeo.txt 并逐行读取。对于每一行,使用 split() 方法将该行拆分为一个单词列表。该程序应该建立一个单词列表。对于每行上的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对生成的单词进行排序和打印。

http://www.pythonlearn.com/code/romeo.txt

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

【问题讨论】:

  • 使用 join ' '.join(lst) 去掉 []。此外,如果您想检查重复项,最好使用集合而不是列表。

标签: list sorting split append


【解决方案1】:

正如 cmets 中提到的那样,set 会更好,但由于任务是关于列表的,请尝试以下操作:

list_of_words = []
with open('romeo.txt') as f:
    for line in f:
        words = line.split()
        for word in words:
            if word not in list_of_words:
                list_of_words.append(word)

sorted_list_of_words = sorted(list_of_words)
print(' '.join(sorted_list_of_words))

输出:

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

向用户询问文件名、使用 continue 并与 python 2.x 兼容的替代解决方案:

fname = raw_input('Enter file: ')

wordlist = list()
for line in open(fname, 'r'):
    words = line.split()
    for word in words:
        if word in wordlist: continue
        wordlist.append(word)

wordlist.sort()
print ' '.join(wordlist)

输出:

Enter file: 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

【讨论】:

    猜你喜欢
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2019-05-05
    相关资源
    最近更新 更多