Python - Count consecutive values without sort

时间:2018-02-03 11:13:21

标签: python arrays

I am trying to build 2 different functions in Python.

strip consecutive values: desired outcome:

exampleArrray = [0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0]
strippedArray = [0,1,2,1,2,1,2,1,2,1,0] 

What I have tried so far:

def stripArray(array):
    lengthArray = len(array)
    for i in range (1,lengthArray):
        print(i)
        print(lengthArray)
        if (i<lengthArray):
            if(array[i-1] == array[i]):

                print("has been delted " + str(array[i]))   
                del(array[i])
                i = i -1
                lengthArray = lengthArray -1     
        print(array)

stripArray([0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0])

Outputs: [0, 0, 1, 1, 1, 2, 2, 1, 2, 1, 2, 1, 2, 2, 2, 1, 1, 0], I could loop again but I think there is a better approach somewhere?

count consecutive values and join

Pseudo: 4x0, 6x1, 3x2, 2x1, 1x2, 1x1, 1x2, 2x1, 6x2, 4x1, 2x0

exampleArrray = [0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0]
   countArray = [40,61,32,21,12,11,12,21,62,41,20]

I think I'll need the stripArray for this?

Edit:

countArray[0] = OccurencesAfterAnother*10  + stripArray[0]

SOLVED: We have 3 perfect funtioning answers! Thank you all! Your Answers couldnt be more different and i really like them all!

Edit: Thank you all for contributing to the accepted answer! Also future viewers, there are different solutions to this, not all of them need imports and others are using numpy approach. Thanks to all contributors!

6 个答案:

答案 0 :(得分:0)

Your stripArray may look like this:

def stripArray(array):
    last = None
    output = []
    for i in array:
        if i != last:
            output.append(i)
            last = i
    return output

I haven't understand the countArray, so I cannot help. Maybe you should provide more details

UPDATE:

def countArray(array):
last = None
output = []
count = 0
for i in array:
    if last is not None and i != last:
        output.append(10*count+last)
        count = 1
    else:
      count += 1
    last = i
output.append(10*count+last)
return output

答案 1 :(得分:0)

您想要对值进行分组,因此我们使用itertools.groupby

>>> from itertools import groupby
>>> example_list = [0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0]
>>> [v for (v, _) in groupby(example_list)]
[0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0]

要获取第二个列表,假设值始终在0到9之间:

>>> [10 * len(list(vs)) + v for (v, vs) in groupby(example_list)]
[40, 61, 32, 21, 12, 11, 12, 21, 62, 41, 20]

答案 2 :(得分:0)

以下工作通过比较exampleArray的每个项目与strippedArray的最后添加项目:

strippedArray = [exampleArrray[0]]
for i in exampleArrray:
    if i != strippedArray[-1]:
        strippedArray.append(i)

输出:

[0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0]

计算和加入:

templist = [exampleArray[0]]
outlist = []
for i in exampleArray[1:]:
    if i == templist[0]:
        templist.append(i)
    else:
        outlist.append(str(len(templist))+str(templist[0]))
        templist = [i]
outlist.append(str(len(templist))+str(templist[0]))
print(outlist)

输出:

['40', '61', '32', '21', '12', '11', '12', '21', '62', '41', '20']

获取整数列表:

outlist = [int(i) for i in outlist]
print(outlist)

输出:

[40, 61, 32, 21, 12, 11, 12, 21, 62, 41, 20]

答案 3 :(得分:0)

这是一种方式:

from itertools import zip_longest
import numpy as np

v = [0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0]
v_arr = np.array(v)

arr_stripped = [i for i, j in zip_longest(v, v[1:]) if i != j]
# [0, 1, 2, 1, 2, 1, 2, 1, 2, 1, 0]

indices = np.hstack((np.array([-1]), np.where(v_arr[:-1] != v_arr[1:])[0], np.array([len(v_arr)-1])))
values = [indices[i+1]-indices[i] for i in range(0, len(indices)-1)]
# [4, 6, 3, 2, 1, 1, 1, 2, 6, 4, 2]

result = [int(str(v)+str(c)) for v, c in zip(values, arr_stripped)]
# [40, 61, 32, 21, 12, 11, 12, 21, 62, 41, 20]

答案 4 :(得分:0)

试试这个

from itertools import groupby

count_dups = [sum(1 for lis in group) for lis, group in groupby(exampleArrray)]
strippedArray =[lis  for lis, group in groupby(exampleArrray)]
countArray= [int(str(v)+str(c)) for v, c in zip(count_dups, strippedArray)]

输出

  

[4,6,3,2,1,1,1,2,6,4,2]

     

[0,1,2,1,2,1,2,1,2,1,0]

答案 5 :(得分:0)

您可以在不导入任何模块的情况下执行此类操作:

exampleArrray= [0,0,0,0,1,1,1,1,1,1,2,2,2,1,1,2,1,2,1,1,2,2,2,2,2,2,1,1,1,1,0,0]

def count_join(e):
    indexs = []
    for i, j in enumerate(e):
        try:
            if e[i] != e[i + 1]:
                indexs.append(i)
        except IndexError:
            pass
    print(indexs.insert(0, -1))

    final_output = []
    for i in range(0, len(indexs), 1):
        c = indexs[i:i + 2]

        if len(c) > 1:

            final_output.append(int(((str(len(e[c[0] + 1:c[1] + 1]))) + str(e[c[0] + 1:c[1] + 1][0]))))
        else:
            final_output.append(int((str(len(e[c[0] + 1:])) + str(e[c[0] + 1:][0]))))

    return final_output



print(count_join(exampleArrray))

输出:

[40, 61, 32, 21, 12, 11, 12, 21, 62, 41, 20]