将数字列表拆分为具有连续数字的子列表

时间:2019-12-17 15:31:53

标签: python list numbers

我想将数字列表中的数字分组为子列表。在子列表中,必须是连续数字

输入 ==> [-4,-3,-2,0,1,3,5,6,7,17,18,30] 输出 ==> [[-4,-3,-2],[0,1],[3],[5,6,7],[17,18],[30]]

最好不带库(仅泛型)

3 个答案:

答案 0 :(得分:1)

为此,您可以简单地使用for循环。一遍是我们能做的最好的-我们必须对每个元素检查一次。 big-O notation中的O(n)。

请记住,列表必须进行排序,否则将无法正常工作。

代码:

inpt = [-4,-3,-2,0,1,3,5,6,7,17,18,30]

rv = []

# Set up current list with first element of input
curr = [inpt[0]]

# For each remaining element:
for x in inpt[1:]:
    # If the next element is not 1 greater than the last seen element
    if x - 1 != curr[-1]:
        # Append the list to the return variable and start a new list
        rv.append(curr)
        curr = [x]
    # Otherwise, append the element to the current list.
    else:
        curr.append(x)
rv.append(curr)

输出:

>>> rv
[[-4, -3, -2], [0, 1], [3], [5, 6, 7], [17, 18], [30]]

答案 1 :(得分:0)

两个指针的解决方案

a = [-4,-3,-2,0,1,3,5,6,7,17,18,30]
slow, fast = 0,0
ans, temp = [], []
while fast < len(a):
    if fast - slow == a[fast] - a[slow]:
        temp.append(a[fast])
        fast += 1
    else:
        slow = fast
        ans.append(temp)
        temp = []
if fast > slow:
    ans.append(temp)
print(ans)

答案 2 :(得分:0)

生成器可以很好地解决这种问题。

代码

def group_me(list):
    list.sort()
    sublist = []

    while list:
        v = list.pop(0)

        if not sublist or sublist[-1] in [v, v-1]:
            sublist.append(v)
        else:
            yield sublist
            sublist = [v]

    if sublist:
        yield sublist


list = [-4, -3, -2, 0, 1, 3, 5, 6, 7, 17, 18, 30]
result = [sublist for sublist in group_me(list)]
print(result)

输出

[[-4, -3, -2], [0, 1], [3], [5, 6, 7], [17, 18], [30]]

注释

如果输入列表中有重复项,则会将它们放入相同的子列表中。