Sigurd
Sigurd

Reputation: 19

Slice a list in python

I have a list in python like:

l = [1,2,4,5,7,8,2,1]

I want a code that will check if the number before in the list is bigger that the next one. And if it is i want the code to remove the the number. I want my code to return [1,2,4,5,7,8] and remove the last 2 and 1.

Pseudo code:

If l[i] > l[i+1]
remove l[i+1]
then check if l[i] is bigger than the next one after that. What use to be l[i+2]

Can someone help me?

Upvotes: 1

Views: 86

Answers (4)

doze
doze

Reputation: 285

you can do this even in one line:

     l = l[0:1] + [el for index,el in enumerate(l[0:])  if el >l[index-1]]
     #l[0:1] + is ugly but i couldnt figure out another way to get the
     #first element since in python l[-1] = l[len(l)-1]

Upvotes: 0

dawg
dawg

Reputation: 103844

You can use itertools groupby to find areas of lists that fulfill a condition; in this case, each number is larger than the number proceeding:

from itertools import groupby 

l = [1,2,4,5,7,8,2,1]

for k, g in groupby(enumerate(l[1:],1), key=lambda (i,e): e>l[i-1]):
    if k:
        grp=list(g)
        print l[grp[0][0]-1:grp[-1][0]+1]
        # [1, 2, 4, 5, 7, 8]

This will find any area in the list that meets that condition:

l = [1,2,4,5,7,8,2,5]

for k, g in groupby(enumerate(l[1:],1), key=lambda (i,e): e>l[i-1]):
    if k:
        grp=list(g)
        print l[grp[0][0]-1:grp[-1][0]+1]
        # prints [1, 2, 4, 5, 7, 8] and [2, 5]

So break after the first if you only want 1 group:

l = [10, 11, 12, 1, 2]
for k, g in groupby(enumerate(l[1:],1), key=lambda (i,e): e>l[i-1]):
    if k:
        grp=list(g)
        print l[grp[0][0]-1:grp[-1][0]+1]
        break
        # [10, 11, 12]

Upvotes: 0

Pacified
Pacified

Reputation: 175

Started with your list and appended based upon your criteria to a new one.

l = [1,2,4,5,7,8,2,1]

result = [] 
chk = 0 

for num in l:

  if chk > num:
    pass
  else:
    chk = num
    result.append(num)

print result

Apparently it is bad practice to delete entries from lists within a loop , so this is a workaround.

Upvotes: 1

Pafycio
Pafycio

Reputation: 19

Iterating through array if there is array[i] > array[i+1] then remove array[i+1].

array = [1,2,4,5,7,8,2,1]
l = len(array)

first = 0
secound = 1

while secound != l:
    if array[first] > array[secound]:
        del array[secound]
        l -= 1
    else:
        first += 1
        secound += 1

print(array)

Upvotes: 0

Related Questions