简体   繁体   English

从readlines()中删除行

[英]Deleting lines from readlines()

f = open('df.txt','r')
l = f.readlines()
for x in l:
    print(x)
    for n in l:
        if x == n:
            l.remove(n)

I want to create a list, print variables in order and delete same variables from the list if there are. 我想创建一个列表,按顺序打印变量,如果有,请从列表中删除相同的变量。 Example: one two three one four 1- It must print "one", and delete [0] and [3] from the list. 示例:一二三一四有四1-它必须打印“一”,并从列表中删除[0]和[3]。

but it skips variables when I run. 但是我运行时会跳过变量。

It's best not to change length of a list during iteration, so append what you want to a new list and skip what you don't 最好不要在迭代过程中更改列表的长度,因此将想要的内容追加到新列表中,然后跳过不需要的内容

mylist = []
f = open('df.txt','r')
l = f.readlines()
for x in l:
    print(x)
    for n in l:
        if x != n:
            mylist.append(x)

recent versions of Python have a Dict implementation that retains its insertion order, so you could also write: 最新版本的Python具有保留其插入顺序的Dict实现,因此您还可以编写:

lines = 'one two three one four'.split(' ')

list(dict((l, None) for l in lines))

Output: 输出:

['one', 'two', 'three', 'four']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM