1

I have a list as follows: a = [1, 2, 1, 1, 2, 3, 1, 2]

I want to implement the following scenarios:

  • If an element in the list is 1 (a[2]) and if the previous element (a[1]) is greater than 1, I want to extract a[1]
  • If an element in the list is 1 (a[3]), and if the previous element is also 1 (a[2]), I want to extract a[2]
  • And in the end, the last element should also be extracted

From the above list, it should be: [2, 1, 3, 2]

I tried:

a = [1, 2, 1, 1, 2, 3, 1, 2]
b = []
i = 0
while (i < len(a)-1):
    print(i)
    c = a[i]
    d = a[i+1]
    
    if d < c:
        b.append(c)
    elif d == c == 1:
        b.append(c)

    i+=1

b.append(a[-1])

Even though it works, I feel it is a really messy solution. I am sure there are better ways to implement this.

Can anyone please suggest a better way to achieve this?

Thanks

reinhardt
  • 1,270
  • 1
  • 7
  • 21

0 Answers0