delete lines

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • antar2

    delete lines

    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("ite m\[1\]\:")
    g = re.compile("ite m\[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!
  • Peter Otten

    #2
    Re: delete lines

    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("ite m\[1\]\:")
    g = re.compile("ite m\[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

    Comment

    Working...