如何在列表中查找重复项,但忽略它第一次出现的情况?

2024-09-29 01:29:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个txt文件中取出了40个单词的列表。我找到了重复的词,并用相同的词替换了它们,但前后都用“*”代替。代码如下:

def show(self, list1):
    a = [x for x in list1 if list1.count(x) > 1]
    lista2 = ["*"+s+"*" if s in a else s for s in list1]
    print(lista2)

输入:

^{pr2}$

输出:

> ['utanför', 'dörren', 'stod', 'en', 'man', '*och*', 'lyssnade', 'intensivt', '*i*', 'den', 'mörka', 'korridoren', '*han*', 'hade', 'skuggat', 'digby', 'groat', 'hela', 'eftermiddagen', '*och*', 'följt', 'efter', 'honom', '*in*', '*i*', 'huset', 'när', '*han*', 'fick', 'hära', 'ljudet', 'av', 'fotsteg', 'från', 'rummet', 'smög', '*han*', 'sig', '*in*', '*i*']

请注意,副本的前面和后面都有一个*。在

我希望第一个副本被忽略,其余的在前面和后面用*突出显示。在

编辑:

def show(self, list1):
    new_list, seen = [], set()
    for x in list1:
        if x in seen:
            new_list.append('*{0}*'.format(x))
        else:
            new_list.append(x)
            seen.add(x)
    print new_list

看起来很有魅力。 现在我唯一想补充的是使它区分大小写。好像“汉”和“汉”发生了,它注意到它是一个复制品。在


Tags: inselfnewforifdefshowelse
3条回答

如果元素出现在切片列表中,则迭代并将其替换为星号版本。使用enumerate跟踪当前索引

lista2 = [s if s not in lista[:i] else '*'+s+'*' for i,s in enumerate(a)]
def show(self, list1):
    new_list, seen = [], set()
    for x in list1:
        if x in seen:
            new_list.append('*{0}*'.format(x))
        else:
            new_list.append(x)
            seen.add(x)
    print new_list

使用set来跟踪看到的项目:

>>> seen = set()
>>> new_lis = []
for x in lis:
    if x in seen:     #if item is present in the set `seen` then add the `*`'s
        new_lis.append('*' + x + '*')
    else:    
        seen.add(x)   #item seen for the first time, add it to the set and the list 
        new_lis.append(x)

使用生成器函数:

^{pr2}$

相关问题 更多 >