Python计数器比较为袋型 [英] Python Counter Comparison as Bag-type

查看:104
本文介绍了Python计数器比较为袋型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我需要一个类似于bag/multiset的数据类型.我了解collections.Counter通常用于此目的.但是比较运算符似乎不起作用:

I need a bag/multiset-like data type in Python. I understand collections.Counter is often used for this purpose. But the comparison operators don't seem to work:

In [1]: from collections import Counter

In [2]: bag1 = Counter(a=1, b=2, c=3)

In [3]: bag2 = Counter(a=2, b=2)

In [4]: bag1 > bag2
Out[4]: True

对我来说,这似乎是个错误.我期望小于和大于运算符执行类似集合的子集和超集比较.但是,如果是这种情况,则bag1 > bag2将为假,因为bag2包含一个额外的'a'. Counter对象上似乎也没有子集/超集方法.所以我有两个问题:

This seems like a bug to me. I expected the less-than and greater-than operators to perform set-like subset and superset comparisons. But if that were the case then bag1 > bag2 would be false because bag2 contains an extra 'a'. There also don't seem to be subset/superset methods on Counter objects. So I have two questions:

  1. Counter对象使用哪种比较逻辑?
  2. 如何比较Counter对象的子集,超集,适当子集和适当超集?

推荐答案

在Python 2上,比较结果回落到

On Python 2, the comparison falls back to the default sort order for dictionaries (Counter is a subclass of dict).

映射(字典)在且仅当其排序时比较相等 (键,值)列表比较相等. [5]除平等外,其他结果是 一致地解决,但没有其他定义. [6]

Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equal. [5] Outcomes other than equality are resolved consistently, but are not otherwise defined. [6]

在Python 3上,比较得出TypeError :

On Python 3, the comparison raises a TypeError:

当且仅当映射(字典)具有 相同(键,值)对.订单比较(<",< =",> =",>") 提高TypeError.

Mappings (dictionaries) compare equal if and only if they have the same (key, value) pairs. Order comparisons ('<', '<=', '>=', '>') raise TypeError.

这篇关于Python计数器比较为袋型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆