加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python计数器比较为袋式

发布时间:2020-12-20 13:44:39 所属栏目:Python 来源:网络整理
导读:我需要 Python中的包/多??类数据类型.我理解collections.Counter经常用于此目的.但比较运算符似乎不起作用: In [1]: from collections import CounterIn [2]: bag1 = Counter(a=1,b=2,c=3)In [3]: bag2 = Counter(a=2,b=2)In [4]: bag1 bag2Out[4]: True 这
我需要 Python中的包/多??类数据类型.我理解collections.Counter经常用于此目的.但比较运算符似乎不起作用:

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对象上似乎也没有子集/超集方法.所以我有两个问题:

> Counter对象使用什么比较逻辑?
>如何比较子对象,超集,正确子集和正确超集的计数器对象?

解决方法

在Python 2上,比较可以追溯到 default sort order for dictionaries(Counter是dict的子类).

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,the comparison raises a TypeError上:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读