我正在梳理如下所示的元組串列:
list1 = [('word', 3), ('example', 2), ('another', 1)]
list2 = [('and', 1), ('word', 4)]
我想將它們組合起來,以便在添加第二個值時洗掉重復項,這里的結果如下所示:
result = [('word', 7), ('example', 2), ('another', 1), ('and', 1)]
我必須實作的代碼是這樣的:
def combineTokenCount(list1, list2):
tokenCount = {}
list = list1 list2
for word in list:
if word[0] not in tokenCount:
tokenCount[word[0]] = int(word[1])
else:
tokenCount[word[0]] = int(word[1])
tokenCount = [(k,v) for k,v in tokenCount.items()]
tokenCount.sort(key = lambda x: x[1], reverse=True)
return tokenCount
這有效,但效率低下。有一個更好的方法嗎?
uj5u.com熱心網友回復:
使用collections.Counter.
>>> from collections import Counter
>>> c = Counter()
>>> c.update(dict(list1))
>>> c.update(dict(list2))
>>> c
Counter({'word': 7, 'example': 2, 'another': 1, 'and': 1})
或在一行中,
c = Counter(dict(list1)) Counter(dict(list2))
Counter是 的子類dict,但如果你真的想要一個平原dict,你可以這樣做
d = dict(c)
uj5u.com熱心網友回復:
嘗試:
>>> list({k: dict(list1).get(k,0) dict(list2).get(k,0) for k in dict(list1 list2)}.items())
[('word', 7), ('example', 2), ('another', 1), ('and', 1)]
uj5u.com熱心網友回復:
from collections import Counter
list1 = [('word', 3), ('example', 2), ('another', 1)]
list2 = [('and', 1), ('word', 4)]
def ourfunct(list1,list2):
result=Counter(dict(list1)) Counter(dict(list2))
final = list(dict(result).items())
return(final)
[('word', 7), ('example', 2), ('another', 1), ('and', 1)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448674.html
上一篇:噪聲影像Python上的矩形檢測
