delete lines

A

antar2

I am new in python and I have the following problem:

Suppose I have a list with words of which I want to remove each time
the words in the lines below item1 and above item2:

item1
a
b
item2
c
d
item3
e
f
item4
g
h
item1
i
j
item2
k
l
item3
m
n
item4
o
p

I did not find out how to do this:

Part of my script was

f = re.compile("item\[1\]\:")
g = re.compile("item\[2\]\:")
for i, line in enumerate(list1):
f_match = f.search(line)
g_match = g.search(line)
if f_match:
if g_match:
if list1 > f_match:
if list1 < g_match:
del list1


But this does not work

If someone can help me, thanks!
 
P

Peter Otten

antar2 said:
I am new in python and I have the following problem:

Suppose I have a list with words of which I want to remove each time
the words in the lines below item1 and above item2:
f = re.compile("item\[1\]\:")
g = re.compile("item\[2\]\:")
for i, line in enumerate(list1):
                f_match = f.search(line)
                g_match = g.search(line)
                if f_match:
                        if g_match:
                                if list1 > f_match:
                                        if list1 < g_match:
                                                del list1


But this does not work

If someone can help me, thanks!


I see two problems with your code:

- You are altering the list while you iterate over it. Don't do that, it'll
cause Python to skip items, and the result is usually a mess. Make a new
list instead.

- You don't keep track of whether you are between "item1" and "item2". A
simple flag will help here.

A working example:

inlist = """item1
a
b
item2
c
d
item3
e
f
item4
g
h
item1
i
j
item2
k
l
item3
m
n
item4
o
p
""".splitlines()

print inlist

outlist = []
between = False

for item in inlist:
if between:
if item == "item2":
between = False
outlist.append(item)
else:
outlist.append(item)
if item == "item1":
between = True

print outlist

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top