题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
str_in = list(input()) sorted_str = sorted(set(str_in)) sorted_str_by_count = sorted(sorted_str, key=lambda x:str_in.count(x), reverse=True) print(''.join(sorted_str_by_count))
首先使用集合set()取出不重复的字符串,并排序,得到按ASCII码升序排序的str list。
然后用sorted()函数对sorted_str中的字符进行排序,排序的依据是每个字符在原始字符串str_in中出现的次数。lambda x: str_in.count(x)是一个匿名函数,用于返回字符在str_in中的出现次数。reverse=True参数表示按降序排序。
使用''.join()函数将sorted_str_by_count列表中的字符拼接成一个新的字符串,并使用print()函数打印出来。
带入具体的例子如下
str_in = aaddccdc
sorted_str = acd
sorted_str_by_count = cda