从列表中替换重复的项目,同时保持第一次出现 [英] Replace duplicate items from list while keeping the first occurrence

查看:82
本文介绍了从列表中替换重复的项目,同时保持第一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表lst = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4]

我期待以下输出:

out = [1,"","",2,"","","",3,"","","","",4,"","","","","","","",""]

我想保留该项目的第一个匹配项,并用空字符串替换同一项目的所有其他匹配项.

I want to keep the first occurrence of the item and replace all other occurrences of the same item with empty strings.

我尝试了以下方法.

`def splrep(lst):
    from collections import Counter
    C = Counter(lst)
    flst = [ [k,]*v for k,v in C.items()]
    nl = []
    for i in flst:
        nl1 = []
        for j,k in enumerate(i):
            nl1.append(j)
        nl.append(nl1)

    ng = list(zip(flst, nl))
    for i,j in ng:
        j.pop(0)
    for i,j in ng:
        for k in j:
            i[k] = ''
    final = [i for [i,j] in ng]
    fin = [i for j in final for i in j]
    return fin`

但是我正在寻找一些更简单或更好的方法.

But I'm looking for some simpler or better approaches.

推荐答案

使用

Use itertools.groupby, quite appropriate for grouping consecutively duplicate values.

from itertools import groupby
[v for k, g in groupby(lst) for v in [k] + [""] * (len(list(g))-1)]
# [1, '', '', 2, '', '', '', 3, '', '', '', '', 4, '', '', '', '', '', '', '', '']

如果您的列表值不是连续的,则可以先对它们进行排序.

If your list values are not consecutive, you may sort them first.

这篇关于从列表中替换重复的项目,同时保持第一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆