简体   繁体   中英

out of order list items in python

Assume I have a list:

lst = [12, 12, 12, 6, 12, 12, 1, 13, 48, 14]

What I want to do is to get out-of-order items. In that case, these would be:

[6, 1, 48]

The correct order of this list is increasing one: [12, 12, 12, 12, 12, 13, 14] but the max increase can be by only one number. For example, in [1, 2, 9, 3] , 9 would be out-of-order.

What I am currently doing is:

for idx in range(1, len(lst)): 
    if lst[idx] < lst[idx-1]: # if item is smaller than the previous one
        print(lst[idx])

[out:] 6
       1
       14

How to update the code so that the output would be correct? I cannot capture numbers that are 'increasing too much', such as 48 in my example list.

If I interpret your definition of out of order correctly, then following should do the job:

start with the first value and accept identical values or a value that is greater by one. and add all other values to your result

#!/usr/bin/env python

def get_ooo(lst):
    if len(lst) == 0:
        return []
    rslt = []
    prev_val = lst[0]
    for val in lst[1:]:
        if val == prev_val:
            continue
        if val == prev_val + 1:
            prev_val = val
            continue
        rslt.append(val)
    return rslt


lst = [12, 12, 12, 6, 12, 12, 1, 13, 48, 14]
print(get_ooo(lst))

or a slightly modified version also doing the job:

def get_ooo(lst):
    if len(lst) == 0:
        return []
    rslt = []
    prev_val = lst[0]
    for val in lst[1:]:
        if prev_val <= val <= prev_val + 1:
            prev_val = val
            continue
        rslt.append(val)
    return rslt

If you also want to know the index of the out-of-order numbers you could do something like:

def get_ooo(lst):
    if len(lst) == 0:
        return []
    rslt = []
    prev_val = lst[0]
    for idx, val in enumerate(lst[1:], 1):
        if prev_val <= val <= prev_val + 1:
            prev_val = val
            continue
        rslt.append((idx, val))
    return rslt

and you would have a list of tuples of position, value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM