python查询字符串中字符出现的次数并按照次数排序
时间: 2023-11-28 09:04:46 浏览: 32
可以使用Python中的字典和Counter来实现。具体代码如下:
```python
from collections import Counter
s = "hello world"
counter = Counter(s)
char_count = {char: count for char, count in sorted(counter.items(), key=lambda item: item[1], reverse=True)}
print(char_count)
```
输出结果为:
```
{'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
```
其中,`counter`使用`Counter`类统计字符串中每个字符出现的次数。然后,将其转换为字典`char_count`,并按照出现次数倒序排序。
相关问题
python统计字符串中单词出现次数并进行排序
可以使用 Python 中的字典来统计字符串中单词出现次数,并使用 sorted() 函数进行排序。以下是示例代码:
```python
sentence = "hello world this is a test sentence for testing"
# 将字符串转换为单词列表
words = sentence.split()
# 使用字典统计单词出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按单词出现次数进行排序
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出排序后的单词及其出现次数
for word, count in sorted_words:
print(word, count)
```
输出结果:
```
a 1
for 1
hello 1
is 1
sentence 1
test 1
testing 1
this 1
world 1
```
python中字符串排序
在 Python 中,可以使用 sorted() 函数对字符串进行排序。例如,可以使用以下代码对字符串进行排序:
str = "hello world"
sorted_str = ''.join(sorted(str))
print(sorted_str)
输出结果为:dehllloorw