[英]Python - make non-unique items in list unique by adding count
如何通過連接計數使列表中的項目變得唯一,每個唯一值從 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'
)
你可以使用一個簡單的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']
使用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
實例,同時保存新創建的實例以供下次看到相同的密鑰時使用。
我有一個非常相似的需求,輸出將是:
['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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.