Having trouble with list post-processing

69 Views Asked by At

I have a small program in which post-processing is required on a Python list. These elements are part of the list:

Exit 14:07:11
Entry 14:07:16
Exit 14:07:20
Entry 14:07:24
Exit 14:07:28
Entry 14:07:32
Exit 14:07:36
Entry 14:07:40
Exit 14:07:44

Which is basically a reading of entering and exiting of a person in a room (only one door). So two entries or exits cannot be together. How can I get it in the form:

Entry....
Exit.....
Entry....
Exit.....
Entry....
Exit.....
Entry....
Exit ......

and so on? Here is what I tried, using a for loop, but this doesn't work:

 for i in range(0,len(y)-2):
        if y[i] == y[i+1]:
            y.remove(y[i])
    print y
    # close the cursor object

how can i get in the desired format?

2

There are 2 best solutions below

0
On

ok... so try this, the problem is you are deleting the elements while iterating, so try using list comprehension: -

y = [temp for i,temp in enumerate(y[:-1]) if y[i].split(" ")[0] !=y[i+1].split(" ")[0]] + [y[-1]]
1
On

I don't think it is a good thing to iterate over a list and remove its items at the same time.

Why not using another temporary list ?

tmpList = []
for ele in y : 
    # take last element of the list and compare it with the current one
    if len(tmpList) and tmpList[-1].split(" ")[0] == ele.split(" ")[0] : 
        continue
    tmpList.append(ele)

y = tmpList