【问题标题】:Subtraction of Counter objects with negative values included in result结果中包含负值的 Counter 对象的减法
【发布时间】:2021-06-08 07:19:49
【问题描述】:

我试图以零和负值包含在结果计数器中的方式减去两个计数器对象,但没有得到所需的输出。示例代码块 '`

1- dic = {'1':6 , '2':4 , '3':2}
2- dic2 = {'1':3 , '2':1 , '3':5}
3- obj1 = Counter(dic)
4- obj2 = Counter(dic2)
5- obj = obj1-obj2 
6- print(obj) 
#Output
Counter({'1':3 , '2':3}) #it omits the '3':-3 part

#In line 5 I also used subtract() but it is returning none 
5 - obj = obj1.subtract(obj2)
#output
None

【问题讨论】:

    标签: python-3.x counter


    【解决方案1】:

    obj1 - obj2 对 Counter 的减法只保留正数并返回 Counter,而 obj1.subtract(obj2) 保留负数但它会原地更改 obj1 并返回 None

    因此,你将obj赋值给None,你会发现obj1实际上被减去了。

    obj1 = Counter({'1':6, '2':4, '3':2})
    obj2 = Counter({'1':3, '2':1, '3':5})
    obj = obj1.subtract(obj2)
    print(obj)
    print(obj1)
    

    输出:

    None
    Counter({'1': 3, '2': 3, '3': -3})
    

    您可以只删除分配和print(obj1),或者如果您想保留obj1,请先复制。

    # 1. change obj1
    obj1.subtract(obj2)
    print(obj1)
    # 2. keep obj1
    obj = obj1.copy()
    obj.subtract(obj2)
    print(obj)
    

    【讨论】:

      【解决方案2】:

      您可以为此使用Countersubtract 方法。

      In [23]: c = Counter(a=4, b=2, c=0, d=-2)
          ...: d = Counter(a=1, b=2, c=3, d=4)
          ...: c.subtract(d)
          ...: c
      Out[23]: Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
      

      注意:Counter('abbbc') - Counter('bccd') 也减去计数,但只保留正计数的结果。

      【讨论】:

      • 实际上我正在使用字典创建计数器对象,此后当我使用减法()时,它返回“无”。
      • @Abhist 这应该可以工作obj1.subtract(obj2)
      猜你喜欢
      • 2012-02-15
      • 1970-01-01
      • 2020-08-30
      • 2015-02-13
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      相关资源
      最近更新 更多