El loquillo
El loquillo

Reputation: 11

Remove integer on a list if it is smaller than the previous integer on the list

I have an unordered list of numbers

num_list=[3 4 5 1 2 5 6 3 1 2 6 9]

I want to run through the list and remove all numbers that are smaller than the previous such that the list is ordered in ascending order after deleting such numbers. How can I do that?

Expected output:

num_list=[3 4 5 5 6 6 9]

Upvotes: 0

Views: 1096

Answers (6)

GZ0
GZ0

Reputation: 4263

Here is another one-liner solution using itertools.accumulate.

from itertools import accumulate
result = [n for n, cur_max in zip(l, accumulate(l, max)) if n >= cur_max]

Despite being concise, it is actually much less efficient than the following solution using an explicit for loop. This is also the most efficient solution as of now.

cur_max = l[0]
result = []
for e in l:
    if e >= cur_max:
        cur_max = e
        result.append(e)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195428

Version with itertools.groupby:

from itertools import groupby

num_list=[3, 4, 5, 1, 2, 5, 6, 3, 1, 2, 6, 9]

out = [num_list[0]]
[out.extend(g) for v, g in groupby(num_list[1:], lambda k: k>=out[-1]) if v]

print(out)

Prints:

[3, 4, 5, 5, 6, 6, 9]

Upvotes: 0

Will Da Silva
Will Da Silva

Reputation: 7040

A comprehension could be used for this:

num_list = [3, 4, 5, 1, 2, 5, 6, 3, 1, 2, 6, 9]
(x for i, x in enumerate(num_list) if all(x >= j for j in num_list[:i]))

Though it's not as efficient as yatu's answer.

Upvotes: 0

yatu
yatu

Reputation: 88236

One simple approach would be to iteratively add values from num_list to a new list if they satisfy the condition of being greater than the last appended value:

out = [num_list[0]]
for i in num_list[1:]:
    if i >= out[-1]:
        out.append(i)

print(out)
# [3, 4, 5, 5, 6, 6, 9]

Upvotes: 4

James Liu
James Liu

Reputation: 517

A simple approach using list.pop

num_list = [3, 4, 5, 1, 2, 5, 6, 3, 1, 2, 6, 9]

i = 1

while (i < len(num_list)):
    if num_list[i] < num_list[i - 1]:
        num_list.pop(i)
    else:
        i += 1

print(num_list)

# [3, 4, 5, 5, 6, 6, 9]

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short approach with functools.reduce function:

import functools

num_list = [3,4,5,1,2,5,6,3,1,2,6,9]
res = functools.reduce(lambda x, y: x if y < x[-1] else x + [y],
                       num_list[1:], [num_list[0]])
print(res)

The output:

[3, 4, 5, 5, 6, 6, 9]

Upvotes: 0

Related Questions