How to remove elements from List all elements that are not in the ascending order?

121 Views Asked by At

I'm novice in Python and I have a question.

part 1 How to remove elements from List all elements that are not in the ascending order? Pls make with function.

Input: list1 = [2, 99, 3, 5, 6, 10, 8, 11, 22]
Output : new_list [2, 3, 5, 6, 8, 11, 22]

part 2 How to move the out of order elements to other list? Pls make with function.

Input: list1 = [2, 99, 3, 5, 6, 10, 8, 11, 22]
Output : new_list [99, 8]

My release are following:

list_1 = [2, 4, 3, 5, 33, 6, 10, 8, 11, 22]
def eliminate_element(li):
    return [list_1[0]] + [j for i, j in zip(list_1, list_1[1:]) if i < j]
print(eliminate_element(list_1))
1

There are 1 best solutions below

2
theherk On

You can do these both in one step. This is quite a verbose way to do it, but it should help. Basically, you want two new lists.

l = [2, 4, 3, 5, 33, 6, 10, 8, 11, 22]

ordered = []
unordered = []

high = 0
for item in l:
    if item >= high:
        ordered.append(item)
        high = item
    else:
        unordered.append(item)

print(ordered)
print(unordered)

which yields:

[2, 4, 5, 33]
[3, 6, 10, 8, 11, 22]