Home > Blockchain >  Finding the elements form a repeated list
Finding the elements form a repeated list

Time:12-21

My list is like this [1,1,1,2,2,2,3,3,3,1,1,1,2,2,2] and I want to grab every element only once. The answer I want looks like this [1,2,3,1,2].

I tried to find the answer on Google but was not able to.

CodePudding user response:

Maybe like this:

list = [1,1,1,2,2,2,3,3,3,1,1,1,2,2,2] 
result = []
[result.append(x) for x in list if len(result) == 0 or x != result[-1]]
print(result)

CodePudding user response:

def rle(x):
    prev = x[0]
    val = [prev]
    count = [0]
    
    for curr in arr:
        if curr != prev:
            val.append(curr)
            count.append(1)
            prev = curr
        else:
            count[-1]  = 1
            
    return val, count

rle_val, rle_count = rle([1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2])
rle_val
# [1, 2, 3, 1, 2]
  • Related