本文介绍了Python:如何在列表中找到重复项,并通过重新命名添加渐进字符来更新这些重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的项目列表:



['T1','T2','T2','T2' 'T2','T3','T3']



我需要确保重复的名称是以这样的方式添加的渐进字母:



['T1','T2A','T2B','T2C','T2D','T3A','T3B' ]



,但只有同一项目有超过1次出现。





任何想法?

解决方案
  from collections import Counter 
from string import ascii_uppercase as letters

def gen(L):
c = Counter(L)
for elt,count in c.items():
if count == 1:
yield elt
else:
for letter in letters [:count]:
yield elt + letter

现在:

 >>&g吨; L = ['T1','T2','T2','T2','T2','T3','T3'] 
>>> list(gen(L))
['T2A','T2B','T2C','T2D','T3A','T3B','T1']


I have a list of items like this:

['T1','T2','T2','T2','T2','T3','T3' ]

I need to make sure that duplicates are renamed with a progressive letter added like this:

['T1','T2A','T2B','T2C','T2D','T3A','T3B']

but only if there is more than 1 occurrence of the same item.

Also, is it possible to do so without generating a new list?

Any ideas?

解决方案
from collections import Counter
from string import ascii_uppercase as letters

def gen(L):
    c = Counter(L)
    for elt, count in c.items():
        if count == 1:
            yield elt
        else:
            for letter in letters[:count]:
                yield elt + letter

Now:

>>> L = ['T1','T2','T2','T2','T2','T3','T3']
>>> list(gen(L))
['T2A', 'T2B', 'T2C', 'T2D', 'T3A', 'T3B', 'T1']

这篇关于Python:如何在列表中找到重复项,并通过重新命名添加渐进字符来更新这些重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 06:07