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/