在Python中絮凝数据

J. *_*son 1 python algorithm chunking

我正在努力在我的絮凝功能中找到错误.

该函数的目标是获取一个列表并将每组连续值组合成一个值.例如...

[1, 4, 4, 2, 0, 3, 3, 3] => [1, 4, 2, 0, 3]

现在的功能是......

def flocculate(array):
    for index1, val1 in enumerate(array):
        if val1 == 0 or not not val1:
            new_array = array[index1+1:]
            for index2, val2 in enumerate(new_array):
                if array[index1] == val2:
                    array[index1 + index2 + 1] = False
                else:
                    break
    return [value for value in array if type(value) is not bool]
Run Code Online (Sandbox Code Playgroud)

但是,它似乎没有很好地处理零.

例如,下面显示的输入得到一些零正确,但是错过了其他一些......

[2, 4, 4, 0, 3, 7, 0, 2, 2, 2, 8, 0, 0, 0] => [2, 4, 3, 7, 0, 2, 8, 0]

Pet*_*vaz 6

我想你可能正在寻找itertools.groupby.

此功能收集类似的项目(由可选键功能定义的相似性).

例如:

import itertools

def flocculate(A):
    return [k for k,g in itertools.groupby(A)]

print flocculate([2, 4, 4, 0, 3, 7, 0, 2, 2, 2, 8, 0, 0, 0])
print flocculate([1, 4, 4, 2, 0, 3, 3, 3])
Run Code Online (Sandbox Code Playgroud)

打印:

[2, 4, 0, 3, 7, 0, 2, 8, 0]
[1, 4, 2, 0, 3]
Run Code Online (Sandbox Code Playgroud)