测试python Counter是否包含在另一个Counter中 [英] Test if python Counter is contained in another Counter

查看:126
本文介绍了测试python Counter是否包含在另一个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 Counter b if, and only if, for every key k in a, the value a[k] is less or equal to the value b[k]. The Counter({'a': 1, 'b': 1}) is contained in Counter({'a': 2, 'b': 2}) but it is not contained in Counter({'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屋!

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