Winterflags Winterflags - 1 year ago 77
Python Question

If item in list meets condition, remove item and multiple preceding items

I am looking for a way to remove every nth item (let's call that item

) in a list, and also x number of items directly preceding
in the list, if
meets a condition.

I have been looking around at list comprehensions and iterations but it has been tricky for a novice to find a solution.


myList = ["you", "are", "right", "I", "am", "wrong"]

For every 3rd item, check if
i == "wrong"
If so, remove
and the two (2) items preceding

Effect: The sequence
"I, "am", "wrong"
is deleted from the list.

Answer Source

How about, for your example,

new_list = [v for i, v in enumerate(myList)
            if myList[3*int(i/3)+2] != 'wrong']

This works since you want to not-copy the entire group of 3 items that ends with 'wrong'. It would be more complicated if you wanted to delete only part of that group or some items not in that group. If, for example, you wanted to delete the 'wrong' value and the value just before it, you could use

new_list = [v for i, v in enumerate(myList)
            if myList[3*(i/3)+2] != 'wrong' or i % 3 == 0]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download