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,因为多集中有3个2。如何在python中做同样的事情?
我只能这样设置:ms = {1,2,4,6,3,2,2,1}。该集合也将对元素进行排序,但也会删除重复项。如果我不能使用set,那还有其他数据结构吗?
同样在ms.equal_range(2);
中搜索python中的多个元素,就像在c ++中一样。
答案 0 :(得分:-1)
这适用于未设置的列表,但.count方法可能就是您要查找的内容。
引用文档: list.count(x)的 返回x出现在列表中的次数。 结束语。
例如。
two_three = [2, 4, 5, 2, 2]
print two_three.count(2)
=> 3