Python2.7:通过添加后缀来删除重复数据

2024-09-30 05:32:51 发布

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

我不确定我是否正确地思考了这个问题。我想写一个函数,它获取一个具有重复项的列表,并在列表中添加一个迭代后缀来“重复”该列表。在

例如:

dup_list = ['apple','banana','cherry','banana','cherry','orange','cherry']

目标是回归:

^{pr2}$

我的直觉是在使用while语句迭代列表时使用pop函数,如下所示:

def dedup_suffix(an_list):
dedup=[]
for each in an_list:
    an_list.pop(an_list.index(each)) #pop it out
    i=1 #iterator  
    while each in an_list:
        an_list.pop(an_list.index(each))
        i+=1
        appendage=str(each)+"_"+str(i)
    else:
        appendage=str(each)
    dedup.append(appendage)
return dedup

但是:

>>> dedup_suffix(dup_list)

['apple', 'cherry', 'orange']

感谢你的指点。在


Tags: 函数anapple列表poplistbananacherry
2条回答

您可以使用Counter来跟踪出现的次数。我假设您的示例对于apple是正确的,因此您不想在第一个出现的地方添加一个0。为此,你需要一点逻辑:

from collections import Counter
counter = Counter()

dup_list = ['apple','banana','cherry','banana','cherry','orange','cherry']
deduped = []
for name in dup_list:
    new = name + str(counter[name]) if counter[name] else name
    counter.update({name: 1})
    deduped.append(new)

可以使用集合。计数器对象。然后通过循环生成一个新列表

dup_list = ['apple','banana','cherry','banana','cherry','orange','cherry']
c = Counter(dup_list)

dedup=[]
for w in c:
    n = c[w]
    if n == 1:
        dedup.append(w)
    else:
        for i in range(1,n+1):
            dedup.append(w+str(i))

相关问题 更多 >

    热门问题