Python-通过添加计数使列表中的非唯一项唯一



如何通过串联计数使列表中的项目唯一,每个唯一值从1开始?

例如:

sheep, sheep, tiger, sheep, hippo, tiger

变为:

sheep1, sheep2, tiger1, sheep3, hippo1, tiger2

以下是如何使用Counter来完成此操作。

from collections import Counter
s = ["sheep", "sheep", "tiger", "sheep", "hippo", "tiger"]
u = [ f"{a}{c[a]}" for c in [Counter()] for a in s if [c.update([a])] ]
print(u)
['sheep1', 'sheep2', 'tiger1', 'sheep3', 'hippo1', 'tiger2']

注意,如果字符串可以有数字后缀,这将不足以覆盖所有情况(例如['alpha']*11+['alpha1']将重复'alpha11'(

使用defaultdictcount的组合:

>>> from collections import defaultdict
>>> from itertools import count
>>> s = ["sheep", "sheep", "tiger", "sheep", "hippo", "tiger"]
>>> d = defaultdict(lambda: count(1))
>>> [f'{x}{next(d[x])}' for x in s]
['sheep1', 'sheep2', 'tiger1', 'sheep3', 'hippo1', 'tiger2']

count是一个对象,当你对它进行迭代时,它会产生不断增加的数字;呼叫next会给你序列中的下一个号码。

每次尝试访问新密钥时,defaultdict都会创建一个新的count实例,同时保存新创建的实例以备下次看到相同密钥时使用。

您可以使用一个简单的for循环:

l = ['sheep', 'sheep', 'tiger', 'sheep', 'hippo', 'tiger']
count = {}
output = []
for s in l:
if s in count:
count[s] += 1
else:
count[s] = 1
output.append(f'{s}{count[s]}')
output

输出:

['sheep1', 'sheep2', 'tiger1', 'sheep3', 'hippo1', 'tiger2']

我有一个非常相似的需求,输出是:

['sheep', 'sheep1', 'tiger', 'sheep2', 'hippo', 'tiger1']

我在寻找O(n(解决方案时有点不同,并扩展了dictionary类。

class IncDict(dict):
def __missing__(self,key):
return -1
def __getitem__(self,key):
val = dict.__getitem__(self,key)
val+=1
dict.__setitem__(self,key,val)
if val==0:
return key
else:
return key+str(val)
l = ['sheep', 'sheep', 'tiger', 'sheep', 'hippo', 'tiger']
uniquify = IncDict()
[uniquify[x] for x in l]

输出:

['sheep', 'sheep1', 'tiger', 'sheep2', 'hippo', 'tiger1']

最新更新