我不确定我是否正确地思考了这个问题。我想写一个函数,它获取一个具有重复项的列表,并在列表中添加一个迭代后缀来“重复”该列表。在
例如:
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']
感谢你的指点。在
您可以使用Counter来跟踪出现的次数。我假设您的示例对于
apple
是正确的,因此您不想在第一个出现的地方添加一个0。为此,你需要一点逻辑:可以使用集合。计数器对象。然后通过循环生成一个新列表
相关问题 更多 >
编程相关推荐