4

我不确定我是否正确地考虑了这个问题。我想编写一个函数,它接受一个包含重复项的列表并将一个迭代后缀附加到“重复”列表中。

例如:

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

回归目标:

deduped = ['apple','banana1','cherry1','banana2','cherry2','orange','cherry3']

我的直觉是在使用 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)

['苹果','樱桃','橙子']

感谢任何指针。

4

2 回答 2

4

您可以使用计数器来跟踪出现次数。我假设您的示例对于 是正确的apple,因此您不想在第一次出现时添加零。为此,您需要一些逻辑:

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)
于 2013-06-24T20:17:42.863 回答
1

您可以使用 collections.Counter 对象计算重复的数量。然后通过迭代创建一个新列表

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))
于 2013-06-24T20:24:21.863 回答