Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List split、rstrip、append-in列表的使用_List_Sorting_Split_Append - Fatal编程技术网

List split、rstrip、append-in列表的使用

List split、rstrip、append-in列表的使用,list,sorting,split,append,List,Sorting,Split,Append,这周的作业是关于列表的问题,我无法摆脱列表符号 打开文件romeo.txt并逐行读取。对于每一行,使用split()方法将该行拆分为一个单词列表。程序应该建立一个单词列表。对于每行中的每个单词,检查该单词是否已经在列表中,如果没有,则将其附加到列表中。程序完成后,按字母顺序对生成的单词进行排序和打印 如注释中所述,设置一个set会更好,但由于作业是关于列表的,请尝试以下操作: list_of_words = [] with open('romeo.txt') as f: for lin

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

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


如注释中所述,设置一个
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
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)
向用户请求文件名的替代解决方案,使用continue并与python 2.x兼容:

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
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

通过使用联接“”除去[]。联接(lst)。此外,如果要检查重复项,最好使用集合而不是列表。