python数字重复统计,如何在Python中的列表中将计数数字追加到重复项?

Here is a list containing duplicates:

l1 = ['a', 'b', 'c', 'a', 'a', 'b']

Here is the desired result:

l1 = ['a', 'b', 'c', 'a_1', 'a_2', 'b_1']

How can the duplicates be renamed by appending a count number?

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

解决方案

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))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值