代码之家  ›  专栏  ›  技术社区  ›  DrakeMurdoch

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

  •  1
  • DrakeMurdoch  · 技术社区  · 7 年前

    我有一个清单:

    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']
    

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

    任何帮助都将不胜感激!

    4 回复  |  直到 7 年前
        1
  •  4
  •   Ajax1234    7 年前

    你可以使用列表理解和 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']
    
        2
  •  0
  •   Austin    7 年前

    另一种简单的使用方法 Counter enumerate :

    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']
    
        3
  •  0
  •   taras Hardik Kamdar    7 年前

    另一个可能的线索:

    List2 = [x if List1.count(x) == 1 else x + chr(ord('a') + List1[:i].count(x)) 
             for i, x in enumerate(List1)]
    
        4
  •  0
  •   Nilav Baran Ghosh    7 年前

    下面的解决方案应该可以在一次传递(数组的一次遍历)中解决您的问题。比AJAX1234、奥斯丁和塔拉斯的解决方案要好得多。当然,您可以进一步压缩此代码。

    count = -1
    newList = []
    for indx,ele in enumerate(List1):
        if indx == 0:
            continue
        if List1[indx]==List1[indx-1]:
            count+=1
            newList.append(List1[indx-1]+str(chr(97+count)))
        elif count == -1:
            newList.append(List1[indx-1])
        else:
            count+=1
            newList.append(List1[indx-1]+str(chr(97+count)))
            count = -1
    if count == -1:
        newList.append(List1[indx])
    else:
        count +=1
        newList.append(List1[indx]+str(chr(97+count)))
    
    推荐文章