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,873
  • 3
  • 9
  • 23
  • why is the last 2 selected? –  Feb 24 '22 at 10:34
  • 1
    `b = [x for x, y in list(zip(a, a[1:])) if x>=y] + [a[-1]]` - elegant? Maybe. Compact? Yes. – Larry the Llama Feb 24 '22 at 10:44
  • @LarrytheLlama the `list(...)` is not necessary around the `zip` and this is not what is asked for... This will give *any* element that is greater than its neighbor. Question asks only for greater than 1. Probably an easy fix is `...if x>=y and y==1]` – Tomerikoo Feb 24 '22 at 10:51

0 Answers0