#include <string>
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string,size_t> word_count;
string word;
while(cin >> word)
{
++ word_count[word];
}
for(const auto & w : word_count)
{
cout << w.first << " occurs " << w.second <<
(w.second > 1 ? "times":"time") << endl;
}
return 0;
}
Exécutez comme suit:
entrer
a b abc school school you are a can canner
Production
a occurs 2times
abc occurs 1time
are occurs 1time
b occurs 1time
can occurs 1time
canner occurs 1time
school occurs 2times
you occurs 1time
Le type de dictionnaire dans map et python est similaire, et le code du même type est écrit en python comme suit:
dict1 = {}
while True:
word = input("") #这里注意python中的input是以'\n'为界的,每次输入后都得换行'\n'
if word == 'q':
break
if word in dict1.keys():
dict1[word] += 1
else:
dict1[word] = 1
str1 = ''
for key in dict1.keys():
if dict1[key] > 1:
str1 = 'times'
else:
str1 = 'time'
print(key + " occurs " + str(dict1[key]) + str1)
Exécutez comme suit dans ubuntu:
r@r:~/coml_/python/test$ python3 1.py
Enter a name(enter 'q' to quit):a
Enter a name(enter 'q' to quit):b
Enter a name(enter 'q' to quit):c
Enter a name(enter 'q' to quit):a
Enter a name(enter 'q' to quit):b
Enter a name(enter 'q' to quit):q
a occurs 2times
b occurs 2times
c occurs 1time