[英]Python append Counter to Counter, like Python dictionary update
I have 2 Counters (Counter from collections), and I want to append one to the other, while the overlapping keys from the first counter would be ignored. 我有2个计数器(来自集合的计数器),我想将一个附加到另一个,而第一个计数器的重叠键将被忽略。 Like the dic.update (python dictionaries update)
像dic.update (python词典更新)
For example: 例如:
from collections import Counter
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)
So something like (ignore overlapping keys from the first counter): 所以类似(忽略第一个计数器的重叠键):
# a.update(b)
Counter({'a':4, 'z':1, 'b':2, 'c':3})
I guess I could always convert it to some kind of a dictionary and then convert it back to Counter, or use a condition. 我想我总是可以将它转换成某种字典,然后将其转换回Counter,或使用条件。 But I was wondering if there is a better option, because I'm using it on a pretty large data set.
但我想知道是否有更好的选择,因为我在一个非常大的数据集上使用它。
Counter
is a dict
subclass , so you can explicitly invoke dict.update
(rather than Counter.update
) and pass two counters as the arguments: Counter
是一个dict
子类 ,因此您可以显式调用dict.update
(而不是Counter.update
)并传递两个计数器作为参数:
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)
dict.update(a, b)
print(a)
# Counter({'a': 4, 'c': 3, 'b': 2, 'z': 1})
You can also use dict unpacking
您也可以使用
dict unpacking
from collections import Counter
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)
Counter({**a, **b})
Counter({'a': 4, 'c': 3, 'b': 2, 'z': 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.