实现字符计数功能

## 方法二:使用collections模块

使用Python内置的collections模块,其中Counter类可以快速实现字符计数功能。

```python

from collections import Counter

def char_count(string):

char_counts = Counter(string)

return char_counts

```

使用方法相当简单,只需调用`char_count`函数并将需要查询的字符串传递给该函数,如下所示:

```python

string = "hello world"

char_counts = char_count(string)

print(char_counts)

```

输出结果如下:

```python

Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

```

以上两种方法都可以实现统计字符串中字符数量的功能,使用方法取决于个人的习惯和工作需求。

你可能感兴趣的:(python)