给定一个字符串,打印输出有重复的字符和重复的次数,并且要按照重复的次数升序输出。
时间: 2024-04-30 14:22:54 浏览: 44
可以使用一个字典来记录每个字符出现的次数,然后根据次数进行排序输出。
代码实现如下:
```python
def print_duplicate_chars(string):
char_counts = {}
for char in string:
if char in char_counts:
char_counts[char] += 1
else:
char_counts[char] = 1
duplicates = [(char, count) for char, count in char_counts.items() if count > 1]
duplicates_sorted = sorted(duplicates, key=lambda x: x[1])
for char, count in duplicates_sorted:
print(f"Character '{char}' appears {count} times.")
```
使用示例:
```python
>>> print_duplicate_chars("hello world")
Character 'o' appears 2 times.
Character 'l' appears 3 times.
```
注意,上述实现只输出了有重复的字符,如果需要输出所有字符的出现次数,可以将第5行改为:
```python
duplicates = [(char, count) for char, count in char_counts.items()]
```
阅读全文