我有一个列表:
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']
我可以找到重复项,但是我不确定该怎么做。
任何帮助将不胜感激!
答案 0 :(得分:4)
您可以使用列表推导和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']
答案 1 :(得分:0)
使用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']
答案 2 :(得分:0)
单线的另一个可能的灵魂:
List2 = [x if List1.count(x) == 1 else x + chr(ord('a') + List1[:i].count(x))
for i, x in enumerate(List1)]
答案 3 :(得分:0)
以下解决方案应一次解决您的问题-一次遍历阵列。比Ajax1234,Austin和taras的解决方案性能更高。当然,您可以进一步压缩此代码。
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)))