测试python Counter是否包含在另一个Counter中 [英] Test if python Counter is contained in another Counter
问题描述
如何测试python Counter
使用以下定义包含在另一个 中:
How to test if a python Counter
is contained in another one using the following definition:
一个计数器
a
包含在一个计数器b
中,当且仅当每个键<$ c $a
中的c> k ,值a [k]
小于或等于值b [k]
。Counter({'a':1,'b':1})
包含在Counter({'a':2,'b ':2})
,但它不包含在Counter({'a':2,'c':2})
中。
A Counter
a
is contained in a Counterb
if, and only if, for every keyk
ina
, the valuea[k]
is less or equal to the valueb[k]
. TheCounter({'a': 1, 'b': 1})
is contained inCounter({'a': 2, 'b': 2})
but it is not contained inCounter({'a': 2, 'c': 2})
.
我认为这是一个糟糕的设计选择,但在python 2.x 中,比较运算符( <
,< =
,> =
, >
)不使用先前的定义,因此第三个Counter被认为比第一个Counter大。在python 3.x 中,相反, Counter
是无序类型。
I think it is a poor design choice but in python 2.x the comparison operators (<
, <=
, >=
, >
) do not use the previous definition, so the third Counter is considered greater-than the first. In python 3.x, instead, Counter
is an unorderable type.
推荐答案
我想到的最好的方法是转换我在代码中给出的定义:
The best I came up with is to convert the definition i gave in code:
def contains(container, contained):
return all(container[x] >= contained[x] for x in contained)
但是,如果感到奇怪的是,python没有解决方案,我就必须编写一个函数每个运算符(或创建一个通用运算符并通过比较功能)。
But if feels strange that python don't have an out-of-the-box solution and I have to write a function for every operator (or make a generic one and pass the comparison function).
这篇关于测试python Counter是否包含在另一个Counter中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!