简体   繁体   中英

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.

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:

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

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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