简体   繁体   English

如何检查Python列表中的最大连续数字?

[英]How to check biggest consecutive numbers in a list in Python?

I want to find the largest consecutive numbers in a list and append them to new list. 我想在列表中找到最大的连续数字并将其附加到新列表中。

my_list = [97, 98, 97, 98, 99, 97, 98, 97]

I tried using while loop but when incremented, it isn't appending some numbers. 我尝试使用while循环,但是当递增时,它没有附加一些数字。

final_list = []
j = 0
while j < (len(my_list) - 1):
    if my_list[j] + 1 == my_list[j + 1]:
        final_list.append(my_list[j])
        final_list.append(my_list[j + 1])
        j += 2
    else:
        j += 1    
print(final_list)

The expected output must be final_list = [97,98,99] 预期的输出必须是final_list = [97,98,99]

But my output is 但是我的输出是

final_list = [97,98]

You can use consecutive_groups from more_itertools module: 您可以使用consecutive_groupsmore_itertools模块:

max([list(group) for group in mit.consecutive_groups(my_list)], key=len)

Example : 范例

import more_itertools as mit

my_list = [97, 98, 97, 98, 99, 97, 98, 97]

print(max([list(group) for group in mit.consecutive_groups(my_list)], key=len))
# [97, 98, 99]

Note : Since this is a third-party module, you need to install before trying out - pip install more_itertools. 注意 :由于这是第三方模块,因此您需要先安装才能尝试-pip install more_itertools。

Here a solution without an external tool: 这里是没有外部工具的解决方案:

    my_list = [97, 98, 97, 1, 2, 100, 98, 99, 97, 98, 97];
    #sort list max to min
    my_list.sort(reverse = True)
    # take largest number as starting point
    last_item = my_list[0]
    new_list = [last_item]
    # loop through list for every item to assure that we dont stop too soon
    for i in range(len(my_list)):
        for number in my_list:
            # compare the current number with the last number inserted to new_list
            # if its smaller we add it to the list and update the last item
            if number == last_item-1:
                new_list.append(number)
                last_item = number
    print(new_list)

Please note that this is probably not the most efficient way of doing it. 请注意,这可能不是最有效的方法。

Find the indices where difference between consecutive elements != 1 using np.where and np.diff (returns a tuple, get the first element of tuple which is an array of indices), add 1 to each element to get the endpoints for np.split . 使用np.wherenp.diff查找连续元素!= 1差的索引(返回一个元组,获取元组的第一个元素,它是索引数组),向每个元素加1以获取np.split的端点np.split
Find the largest array from the resulting list using max(list,key=len) 使用max(list,key=len)从结果列表中找到最大的数组

>>> import numpy as np
>>> my_list = [97, 98, 97, 98, 99, 97, 98, 97]
>>> max(np.split(my_list,np.where(np.diff(my_list) != 1)[0]+1),key=len)
array([97, 98, 99])

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

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