輸入:任何pythonic方式做「[['a',2],['b',1]] + [['b',2],['c',1]] = [['b',3 ],['a',2],['c',1]]「?
[['a', 2], ['b',1]] (sorted by value)
[['b', 2], ['c', 1]]
輸出:
[['b', 3], ['a', 2], ['c', 1]]
任何Python的方式?當然,在Python中! (更好的爲2.6x) 謝謝!
輸入:任何pythonic方式做「[['a',2],['b',1]] + [['b',2],['c',1]] = [['b',3 ],['a',2],['c',1]]「?
[['a', 2], ['b',1]] (sorted by value)
[['b', 2], ['c', 1]]
輸出:
[['b', 3], ['a', 2], ['c', 1]]
任何Python的方式?當然,在Python中! (更好的爲2.6x) 謝謝!
使用collections.Counter
爲Python2.7 +:
>>> from collections import Counter
>>> lis1 = [['a', 2], ['b',1]]
>>> lis2 = [['b', 2], ['c', 1]]
>>> c = Counter(dict(lis1)) + Counter(dict(lis2))
>>> c.most_common()
[('b', 3), ('a', 2), ('c', 1)]
如果列表中包含重複的項目,那麼你需要修改Counter
例子是:
>>> lis1 = [['a', 2], ['b',1], ['b',5]]
>>> lis2 = [['b', 2], ['c', 1], ['a', 10]]
>>> from itertools import chain
>>> from collections import Counter
>>> c = sum((Counter(dict([x])) for x in chain(lis1, lis2)), Counter())
>>> c.most_common()
[('a', 12), ('b', 8), ('c', 1)]
爲2.5 < = Python的< = 2.6使用collections.defaultdict
:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for k, v in lis1 + lis2:
d[k] += v
...
>>> sorted(d.items(), key=lambda x:x[1], reverse=True)
[('b', 3), ('a', 2), ('c', 1)]
最後添加:map((x:[x [0],x [1]]),t)? – Kane
@Kane:'map(list,whatever_you_called_the_output)'如果你想要列表而不是元組。 – user2357112
作爲python 2.6收藏的類別爲Counter
,這一個是會做的。人們可以使用defautldict
,但它的使用不簡化代碼:
a = [['a', 2], ['b', 1]]
b = [['b', 2], ['c', 1]]
rv = {}
for k, v in a + b:
rv[k] = rv.setdefault(k, 0) + v
預期結果的輸出繼電器,轉換成列表的列表:
>>> map(list, sorted(rv.items(), key = lambda x: x[1], reverse=True))
[['b', 3], ['a', 2], ['c', 1]]
就拋出這個答案在這裏,但你可能希望將它們組合到一個列表,然後盡數:
>>> a = [['a', 2], ['b',1]]
>>> b = [['b', 2], ['c', 1]]
>>> a + b
[['a', 2], ['b', 1], ['b', 2], ['c', 1]]
>>> "".join(c*n for c, n in a+b)
'aabbbc'
>>> from collections import Counter
>>> Counter("".join(c*n for c, n in a+b))
Counter({'b': 3, 'a': 2, 'c': 1})
>>> Counter("".join(c*n for c, n in a+b)).most_common()
[('b', 3), ('a', 2), ('c', 1)]
您可以簡單地創建類型的字典你的元組(名單列表在這裏你的情況),然後添加他們的計數器。
>>> from collections import Counter
>>> a = [['b', 2], ['c', 1]]
>>> b = [['a', 2], ['b',1]]
>>> sorted(dict(Counter(dict(a)) + Counter(dict(b))).items(),key= lambda x:-x[1])
[('b', 3), ('a', 2), ('c', 1)]
尼斯
從集合導入計數器
LIS1 = [[ '一個',2],[ 'B',1]]
LIS2 = [['b',2],['c',1]]
c = Counter(dict(lis1))+ Count ER(字典(LIS2))
c.most_common()
[('b', 3), ('a', 2), ('c', 1)]
collections.defaultdict在python 2.5和2.6和collections.Counter 2。7和更高
從集合導入defaultdict
d = defaultdict(INT)
爲K,V在LIS1 + LIS2:
d[k] += v
排序(d.items(),鍵=拉姆達X:X [1],反向=真)
[('b', 3), ('a', 2), ('c', 1)]
答案:
>>> from collections import Counter >>> p = [['a', 2], ['b',1]] >>> q = [['b', 2], ['c', 1]] >>> m = Counter(dict(p)) + Counter(dict(q)) >>> sorted(m.items(), key=lambda x:x[1], reverse=True) [('b', 3), ('a', 2), ('c', 1)]
你確定你不想要字典嗎? – user2357112
你想單獨使用列表嗎? –
Coz,輸出將編碼爲JSON。而且,大多數情況下,系統只需要最好的一個。無論如何,這是一個有趣的問題,不是嗎? – Kane