如何将计数数字附加到Python中列表中的重复项? [英] How to append count numbers to duplicates in a list in Python?
本文介绍了如何将计数数字附加到Python中列表中的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是包含重复项的列表:
Here is a list containing duplicates:
l1 = ['a', 'b', 'c', 'a', 'a', 'b']
这是预期的结果:
l1 = ['a', 'b', 'c', 'a_1', 'a_2', 'b_1']
如何通过添加计数来重命名重复项?
How can the duplicates be renamed by appending a count number?
这里是实现这一目标的尝试;但是,还有一种更Python化的方法吗?
Here is an attempt to achieve this goal; however, is there a more Pythonic way?
for index in range(len(l1)):
counter = 1
list_of_duplicates_for_item = [dup_index for dup_index, item in enumerate(l1) if item == l1[index] and l1.count(l1[index]) > 1]
for dup_index in list_of_duplicates_for_item[1:]:
l1[dup_index] = l1[dup_index] + '_' + str(counter)
counter = counter + 1
推荐答案
在Python中,生成新列表通常比更改现有列表容易得多.我们有发电机可以有效地做到这一点.字典可以保留发生次数.
In Python, generating a new list is usually much easier than changing an existing list. We have generators to do this efficiently. A dict can keep count of occurrences.
l = ['a', 'b', 'c', 'a', 'a', 'b']
def rename_duplicates( old ):
seen = {}
for x in old:
if x in seen:
seen[x] += 1
yield "%s_%d" % (x, seen[x])
else:
seen[x] = 0
yield x
print list(rename_duplicates(l))
这篇关于如何将计数数字附加到Python中列表中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文