给定字符串,输出符合要求的子串
给定字符串,输出出现次数>3
的字符串。
实例:
输入:
"kou red game red ok who game red karaoke yukari kou red red nani kou can koukou ongakugame game"
输出:
red
game
kou
代码:
import operator
input_str = "kou red game red ok who game red karaoke yukari kou red red nani kou can koukou ongakugame game"
str_list = input_str.split(" ")
str_set = set(str_list)
str_count_dic = {}
for key in str_set:
str_count_dic[key] = str_list.count(key)
# choose value, more than 3
str_count_more3 = {k: v for k, v in str_count_dic.items() if v >= 3}
# 按照key排序
str_count_key_sorted = dict(sorted(str_count_more3.items(), key=operator.itemgetter(0))) # 对出现次数相同的key进行排序
# 按照value排序
str_count_value_sorted = sorted(str_count_key_sorted.items(), key=lambda x: x[1], reverse=True)
for key in str_count_value_sorted:
print(key[0])