[英]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.此列表的正确顺序是增加一:
[12, 12, 12, 12, 12, 13, 14]
但最大增加只能是一个数字。 For example, in [1, 2, 9, 3]
, 9
would be out-of-order.例如,在
[1, 2, 9, 3]
中, 9
将是无序的。
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?如何更新代码以使 output 正确? I cannot capture numbers that are 'increasing too much', such as
48
in my example list.我无法捕获“增加太多”的数字,例如我的示例列表中的
48
。
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.从第一个值开始并接受相同的值或大于 1 的值。 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你会有一个 position 的元组列表,值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.