在Python中,我试图采取:
mylist=[a,a,a,b,b,c]
并将其变为:
mylist=[(a,0),(a,1),(a,2),(b,0),(b,1),(c,0)]
答案 0 :(得分:0)
以下是使用Counter的解决方案:
from collections import Counter
c = Counter()
l = ['a', 'a', 'a', 'b', 'b', 'c', 'c']
out = []
for e in l:
out.append((e, c[e]))
c[e] += 1
print(out)
这是另一个假设输入列表已排序:
from itertools import groupby
print(tuple((e, idx) for _, group in groupby(l) for idx, e in enumerate(group)))