繁体   English   中英

python 中的乱序列表项

[英]out of order list items in python

假设我有一个列表:

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

我想要做的是得到乱序的物品。 在这种情况下,这些将是:

[6, 1, 48]

此列表的正确顺序是增加一: [12, 12, 12, 12, 12, 13, 14]但最大增加只能是一个数字。 例如,在[1, 2, 9, 3]中, 9将是无序的。

我目前正在做的是:

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

如何更新代码以使 output 正确? 我无法捕获“增加太多”的数字,例如我的示例列表中的48

如果我正确解释了您对无序的定义,那么以下应该可以完成工作:

从第一个值开始并接受相同的值或大于 1 的值。 并将所有其他值添加到您的结果中

#!/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))

或稍作修改的版本也可以完成这项工作:

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

如果您还想知道乱序数字的索引,您可以执行以下操作:

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

你会有一个 position 的元组列表,值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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