我不确定我是否正确地考虑了这个问题。我想写一个函数,它带有一个带有重复项的列表,并附加一个迭代后缀来“删除”列表。
例如:
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)
['apple','cherry','orange']
欣赏任何指示。
答案 0 :(得分:4)
您可以使用Counter来跟踪发生的次数。我假设您的示例相对于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)
答案 1 :(得分: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))