Python(2.7 ....)列出问题

时间:2016-01-22 07:09:29

标签: python list sorting append

我需要一些帮助,我现在正在做一个在线python课程,我似乎可以获得完成作业的愿望结果。

基本上,有一个文本文档,我需要使用“raw_input”调用然后使用“open()”函数,然后我有一个空的“list()”

现在我为.txt doc中的每一行运行一个“for”循环,我需要“r.strip()”所有的空格,这留给我一个4个实时.txt文件(.txt文件将在问的底部)现在我必须“.split()”这些行成文字。现在从我需要循环遍历这些单词和“.append()”每个单词不在列表中,然后“.sort()”然后打印...希望在那个阶段它看起来像所需的输出。 / p>

为了让我感觉好一点这是我第一次进行任何编码。所以,如果你能解释哪里以及为什么我的错误会很好。 CODE SO FAR - 目前产生错误

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    a = line.rstrip()
    b = a.split()
    for words in b:
        if words not in lst:
print lst

.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

p.s - 没有必要将.txt更改为一行,因为它在分级器中不起作用。我试过(得到了想要的输出,错误的代码)

拜托,非常感谢你的帮助。

如果您需要更多信息,请尝试提供。

4 个答案:

答案 0 :(得分:0)

这将读取文件,添加单词列表,对列表进行排序,然后打印。

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    a = line.rstrip()
    b = a.split()
    for words in b:
        if words not in lst:
            lst.append(words)
lst.sort()
print lst
fh.close()

lst.append(element)会将element添加到列表lst

lst.sort()将按字母顺序对列表lst进行排序。

查看文档=> Lists

答案 1 :(得分:0)

l = list()
with open('inp.txt') as inp:
        for each_line in inp:
                a = each_line.strip()
                l += a.split()

print set(l)

使用关键字,因为它是一种更好的做法,因为它会在操作后关闭文件。对于唯一部分,使用set()只接受唯一元素

答案 2 :(得分:0)

你也可以使用set,它就像一个列表,但没有重复。这意味着您不必自己检查重复项,因为set会自动为您执行重复操作。

例如:

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = set()
for line in fh:
    a = line.rstrip()
    b = a.split()
    for words in b:
        lst.add(words)
lst = list(lst)
lst.sort()
print lst

答案 3 :(得分:0)

尝试使用list comprehension生成列表,使用set删除重复的条目

lst = [words for line in open(fname) for words in line.rstrip().split()]
lst = list(set(lst))
lst.sort()
print lst