在列表中查找重复项,并在每次打开后添加连续的字母字符

2024-09-27 09:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单:

List1 = ['M1', 'M2', 'M3', 'M4', 'M5', 'M5', 'M5', 'M6', 'M7', 'M7', 'M8', 'M9', 'M10', 'M10', 'M10', 'M11']

我想找到所有的副本,然后在每个副本后面加上小写字母,这样看起来像这样:

List1 = ['M1', 'M2', 'M3', 'M4', 'M5a', 'M5b', 'M5c', 'M6', 'M7a', 'M7b', 'M8', 'M9', 'M10a', 'M10b', 'M10c', 'M11']

我能找到复制品,但我真的不知道该怎么办。你知道吗

任何帮助都将不胜感激!你知道吗


Tags: 副本m3m5m4m1m2list1小写字母
3条回答

另一个可能的解决方案是一个班轮:

List2 = [x if List1.count(x) == 1 else x + chr(ord('a') + List1[:i].count(x)) 
         for i, x in enumerate(List1)]

您可以使用列表理解和string.ascii_lowercase

import string, collections
def addition(val, _i, l):
   return string.ascii_lowercase[sum(c == val for c in l[:_i])]

List1 = ['M1', 'M2', 'M3', 'M4', 'M5', 'M5', 'M5', 'M6', 'M7', 'M7', 'M8', 'M9', 'M10', 'M10', 'M10', 'M11']
c = collections.Counter(List1)
new_results = ['{}{}'.format(a, '' if c[a] == 1 else addition(a, i, List1)) for i, a in enumerate(List1)]

输出:

['M1', 'M2', 'M3', 'M4', 'M5a', 'M5b', 'M5c', 'M6', 'M7a', 'M7b', 'M8', 'M9', 'M10a', 'M10b', 'M10c', 'M11']

另一种使用Counterenumerate的简单方法:

from collections import Counter

List1 = ['M1', 'M2', 'M3', 'M4', 'M5', 'M5', 'M5', 'M6', 'M7', 'M7', 'M8', 'M9', 'M10', 'M10', 'M10', 'M11']

c = Counter(List1)

prev = List1[0]
for i, x in enumerate(List1):
    if c[x] > 1 and prev != x:
        l = 'a'
        List1[i] += l
        prev = x
    elif c[x] > 1 and prev == x:
        l = chr(ord(l) + 1)
        List1[i] += l

print(List1)
# ['M1', 'M2', 'M3', 'M4', 'M5a', 'M5b', 'M5c', 'M6', 'M7a', 'M7b', 'M8', 'M9', 'M10a', 'M10b', 'M10c', 'M11']

相关问题 更多 >

    热门问题