用python编写程序接收字符串,按字符出现频率的降序打印。
时间: 2023-12-16 13:08:22 浏览: 49
好的,下面是一个简单的实现:
``` python
def print_char_frequency(s):
"""
接收字符串,按字符出现频率的降序打印
:param s: 字符串
"""
char_count = {}
# 遍历字符串,统计每个字符出现的次数
for c in s:
if c in char_count:
char_count[c] += 1
else:
char_count[c] = 1
# 按字符出现次数降序排序
sorted_chars = sorted(char_count.items(), key=lambda x: x[1], reverse=True)
# 打印结果
for c, count in sorted_chars:
print(c, count)
# 测试程序
s = "hello world"
print_char_frequency(s)
```
在这个程序中,我们首先使用一个字典来统计每个字符在字符串中出现的次数,然后使用 `sorted` 函数对字典的键值对进行排序,排序的依据是键值对的值,也就是出现次数。最后,我们遍历排序后的列表,按顺序打印每个字符和它在字符串中出现的次数。
相关问题
Python 编写程序接收字符串,按字符出现频率的降序打印。
好的,你可以参考下面的 Python 代码实现:
```python
string = input("请输入字符串:")
# 统计字符出现频率
freq = {}
for char in string:
freq[char] = freq.get(char, 0) + 1
# 按出现频率降序排序
freq_sorted = sorted(freq.items(), key=lambda x: x[1], reverse=True)
# 打印结果
for char, count in freq_sorted:
print(char, count)
```
这个程序会从用户输入中读取一个字符串,然后统计每个字符出现的频率。最后按照字符出现频率的降序排列,并打印出来。
用python编写程序实现接收字符串并按字符出现频率的降序打印字母
好的,这个问题可以用 Python 中的字典来解决。你可以使用 collections 模块中的 Counter 类来统计字符串中各个字符出现的次数,然后按照出现次数进行降序排列。
下面是一个示例代码:
```python
from collections import Counter
def print_char_by_freq(input_str):
# 统计字符出现次数
char_count = Counter(input_str)
# 按照出现次数降序排列
sorted_char_count = sorted(char_count.items(), key=lambda item: item[1], reverse=True)
# 打印结果
for char, count in sorted_char_count:
print(char, count)
# 测试代码
input_str = "hello world"
print_char_by_freq(input_str)
```
输出结果为:
```
l 3
o 2
h 1
e 1
1
w 1
r 1
d 1
```
代码说明:
1. 首先导入 collections 模块中的 Counter 类。
2. 定义一个函数 `print_char_by_freq`,接受一个字符串参数。
3. 使用 Counter 对象统计字符串中各个字符出现的次数,得到一个字典对象 `char_count`。
4. 使用 sorted 函数对字典对象中的键值对进行排序,按照值进行降序排列,得到一个列表对象 `sorted_char_count`。
5. 遍历排序后的列表对象,依次输出每个字符和对应的出现次数。