【发布时间】:2020-03-24 16:36:54
【问题描述】:
如何通过连接计数来使列表中的项目唯一,每个唯一值从 1 开始?
所以,例如:
sheep, sheep, tiger, sheep, hippo, tiger
变成:
sheep1, sheep2, tiger1, sheep3, hippo1, tiger2
【问题讨论】:
-
我推荐看一下收藏包中的Counter函数,我相信这会帮助你实现你想要的。
如何通过连接计数来使列表中的项目唯一,每个唯一值从 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')
【讨论】:
使用defaultdict 和count 的组合:
>>> 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) 解决方案并扩展字典类时采用了一些不同的方法。
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']
【讨论】: