-1

我有一个这样的项目列表:

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

我需要确保使用这样添加的渐进字母重命名重复项:

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

但仅当同一项目出现超过 1 次时。

另外,是否可以在不生成新列表的情况下这样做?

有任何想法吗?

4

3 回答 3

3
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

现在:

>>> L = ['T1','T2','T2','T2','T2','T3','T3']
>>> list(gen(L))
['T2A', 'T2B', 'T2C', 'T2D', 'T3A', 'T3B', 'T1']
于 2013-06-19T22:46:25.093 回答
0

考虑到列表已排序,这将就地修改列表。如果列表未排序,则可以先使用以下命令对其进行排序lis.sort()

>>> from string import ascii_uppercase
>>> from itertools import groupby
>>> from collections import Counter
>>> lis = ['T1', 'T2', 'T2', 'T2', 'T2', 'T3', 'T3']
>>> c = Counter(lis)
>>> for k, v in groupby(enumerate(lis), key = lambda x:x[1]):
    l = list(v)
    if c[k] > 1:
        for x, y in zip(l, ascii_uppercase):
            lis[x[0]] = x[1] + y
...             
>>> lis
['T1', 'T2A', 'T2B', 'T2C', 'T2D', 'T3A', 'T3B']
于 2013-06-19T22:40:08.307 回答
0
def fix(L):
    d = {}
    for i in xrange(len(L)):
        d[L[i]] = d.get(L[i],0)+1
        if d[L[i]] > 1:
            if d[L[i]] == 2: L[L.index(L[i])] += 'A'
            L[i] += chr(64+d[L[i]])
于 2013-06-19T23:55:10.903 回答