python 查找重复列表中的元素[已关闭]

ztigrdn8  于 2022-12-21  发布在  Python
关注(0)|答案(2)|浏览(128)

7小时前关闭。
Improve this question
我的列表就像[1,1,1,2,2,2,3,3,3,1,1,1,2,2,2],我只想抓取每个元素一次,我想要的答案就像[1,2,3,1,2]
我试图在谷歌上找到答案,但无法找到。

pftdvrlh

pftdvrlh1#

也许像这样:

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)
k2arahey

k2arahey2#

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]

相关问题