在Python中使用Counts来减去字典列表
我已经计算出如何使用“计数器”将字典列表与下面的代码添加列表
from collections import Counter
a = [{'num': 'star1', 'count': 1},
{'num': 'star2', 'count': 3}]
b = [{'num': 'star1', 'count': 7},
{'num': 'star2', 'count': 2},
{'num': 'star3', 'count': 1}]
joint = sum((Counter({elem['num']: elem['count']}) for elem in a + b), Counter())
[{'num': num, 'count': counts} for num, counts in joint .items()]
,但是,当我尝试减去错误时,我会遇到错误。例如:
from collections import Counter
a = [{'num': 'star1', 'count': 1},
{'num': 'star2', 'count': 3}]
b = [{'num': 'star1', 'count': 7},
{'num': 'star2', 'count': 2},
{'num': 'star3', 'count': 1}]
joint = sum((Counter({elem['num']: elem['count']}) for elem in a - b), Counter())
[{'num': num, 'count': counts} for num, counts in joint .items()]
有人知道这项工作吗?还是我如何解决这个问题?
我尝试在计数器中使用减法功能,但似乎仍然不起作用
I've worked out how to use "counter" to add lists of dictionarys with the code below
from collections import Counter
a = [{'num': 'star1', 'count': 1},
{'num': 'star2', 'count': 3}]
b = [{'num': 'star1', 'count': 7},
{'num': 'star2', 'count': 2},
{'num': 'star3', 'count': 1}]
joint = sum((Counter({elem['num']: elem['count']}) for elem in a + b), Counter())
[{'num': num, 'count': counts} for num, counts in joint .items()]
However, when I try to subtract I get an error. For example:
from collections import Counter
a = [{'num': 'star1', 'count': 1},
{'num': 'star2', 'count': 3}]
b = [{'num': 'star1', 'count': 7},
{'num': 'star2', 'count': 2},
{'num': 'star3', 'count': 1}]
joint = sum((Counter({elem['num']: elem['count']}) for elem in a - b), Counter())
[{'num': num, 'count': counts} for num, counts in joint .items()]
Is anyone aware of a work around to this? Or how I could approach this issue?
I've tried using the subtract function in counter but it still doesn't seem to work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为计数器不接受否定计数,但是如果您不介意没有负数,这将起作用(仅分别进行两个计数器):
它输出:
其他值(Star1和Star3)都会少少比0分别达到1-7 = -6 = -6 = -1
,您可以不使用计数器并这样做(这支持负数和您想要的任何操作):
I don't think Counter accept negative counts, but if you don't mind about not having negative counts, this will work (just doing the two Counters separately):
It outputs:
The other values (star1 and star3) would both be less than 0 because they come to 1-7=-6 and 0-1=-1 respectively
Alternatively you can just not use counters and do it like this (this supports negative numbers and whatever operation you want):