python - python 中是否有像 C++11 中那样的多重集的 equal_range?

标签 python c++

I C++11 我可以执行以下操作:

multiset<int> ms {1,2,4,6,3,2,2,1}; // set will sort these elements automatically

std::pair<multiset<int>::iterator, multiset<int>::iterator> bounds;

// look for number 2 in the multiset
bounds = ms.equal_range(2);

for (auto v: ms)
{
    cout << v << " ";
}

它给出 2 2 2 因为多重集中有三个 2。如何在 python 中做同样的事情?

我只能这样设置:ms = {1,2,4,6,3,2,2,1}。该集合也会对元素进行排序,但也会删除重复项。如果我不能使用 set,是否有其他数据结构?

还有什么等效于此 ms.equal_range(2); 在 python 中搜索多个元素,就像在 c++ 中一样。

最佳答案

这适用于列表而不是集合,但是 .count 方法可能正是您要寻找的。

引用文档: 列表.count(x) 返回 x 在列表中出现的次数。 结束报价。

例如。

two_three = [2, 4, 5, 2, 2]
print two_three.count(2)
=> 3

关于python - python 中是否有像 C++11 中那样的多重集的 equal_range?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28759220/

相关文章:

C++ 内存管理和虚拟内存页面大小

c++ - 如何使用 Catch2 和 CMake 添加单独的测试文件?

不同文件中的python相同模块

python - 无法使用 Firefox 驱动程序打开网站

python - 在 pygtk3 中从网络摄像头绘制帧到 DrawableArea 时出现段错误

Python嵌套函数

c++ - 如何使用 void 类型处理递归回溯返回

python - 如何在 SciPy 中获得正确的插值?

c# - 将字符串从 C# 传递到 C++ DLL 并返回——最小示例

c++ - 如何使用Qt检查webservice是否启动