首页 > python列表输出问题

python列表输出问题

1.原文本

we avoid  avoid bois
ccccc  ddddd 1123 1123
fdsaflsj  we

2.我想去除每行的重复元素,代码如下

with open('10.txt', 'r') as f:
    for line in f.readlines():
        i = line.split()
        j = []
        for x in i:
            if not x in j:
                j.append(x)
        print j

3.但输出结果是

['we', 'avoid', 'bois']
['ccccc', 'ddddd', '1123']
['fdsaflsj', 'we']

4.我想要的结果是这样的,如何实现呢?尝试过print j,但元素都输出在一行了。

we avoid  bois
ccccc  ddddd 1123
fdsaflsj

在内循环里输出j, 在内循环结束后输出 '\n'


只需要把输出的 print j 改一下,改成 ' '.joint(j)

如果你只是 print j 那么等效于调用了 print j.__str__(),而这一句是会打印成你原文档的样子的。你也可以继承 list,通过 overwrite 他的 __str__ 也可以达到同样的效果。

例如:

    class List(list):
    
        def __str__(self):
            return ' '.join([str(x) for x in self])
    
    
    l = List(['a', 'b', 'c', 'd'])
    print l

这里有2个点,第一个是__str__;另一个是我str了list中的每个元素,这是为了避免join操作的时候发生错误。

所有代码在Python2.7.10上测试通过


with open('10.txt', 'r') as f:
    for line in f.readlines():
        print " ".join(set(line.split()))

最后print j改成print " ".join(j)


with open('10.txt', 'r') as f:
    for line in f.readlines():
        i = line.split()
        j = []
        for x in i:
            if not x in j:
                j.append(x)
        s = ""
        for elements in j:
            s = s + " " + elements   
        print s
【热门文章】
【热门文章】