Python如何统计列表不同元素出现的次数
时间: 2024-05-12 15:15:09 浏览: 8
可以使用Python内置的collections模块中的Counter类来统计列表中不同元素出现的次数。具体实现如下:
```python
from collections import Counter
lst = [1, 2, 3, 1, 2, 3, 4, 5]
count = Counter(lst)
print(count)
```
输出结果为:
```
Counter({1: 2, 2: 2, 3: 2, 4: 1, 5: 1})
```
其中,Counter对象中的键值对表示列表中的元素及其出现的次数。
相关问题
python统计列表中元素出现的次数
可以使用Python中的collections模块中的Counter函数来统计列表中元素出现的次数。具体操作如下:
1. 导入collections模块
```python
import collections
```
2. 定义列表
```python
lst = [1, 2, 3, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 7, 8, 9]
```
3. 使用Counter函数统计元素出现的次数
```python
count = collections.Counter(lst)
```
4. 输出结果
```python
print(count)
```
输出结果为:
```
Counter({1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2})
```
其中,Counter函数返回的是一个字典,字典的键为列表中的元素,值为该元素在列表中出现的次数。
python 统计列表中 元素出现的次数
可以使用Python内置的count()函数统计列表中元素出现的次数,示例代码如下:
```python
my_list = [1, 2, 3, 2, 1, 2, 3, 4]
for i in set(my_list):
print("元素", i, "出现了", my_list.count(i), "次")
```
输出结果:
```
元素 1 出现了 2 次
元素 2 出现了 3 次
元素 3 出现了 2 次
元素 4 出现了 1 次
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)