delete lines
Peter Otten
__peter__ at web.de
Wed Jul 9 06:09:01 EDT 2008
antar2 wrote:
> 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[i] > f_match:
> if list1[i] < g_match:
> del list1[i]
>
>
> 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
More information about the Python-list
mailing list