3 回答
TA贡献1852条经验 获得超7个赞
Python3代码:
import collections
stringlist = ["Cat","Cat","Cat","Dog","Dog","Lizard"]
counterinstance = collections.Counter(stringlist)
for key,value in counterinstance.items():
print(key,":",value)
C++代码:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main()
{
unordered_map <string,int> counter;
vector<string> stringVector {"Cat","Cat","Cat","Dog","Dog","Lizard"};
for (auto stringval: stringVector)
{
if (counter.find(stringval) == counter.end()) // if key is NOT present already
{
counter[stringval] = 1; // initialize the key with value 1
}
else
{
counter[stringval]++; // key is already present, increment the value by 1
}
}
for (auto keyvaluepair : counter)
{
// .first to access key, .second to access value
cout << keyvaluepair.first << ":" << keyvaluepair.second << endl;
}
return 0;
}
输出:
Lizard:1
Cat:3
Dog:2
添加回答
举报