python统计列表出现次数次数最多的元素
时间: 2023-05-29 07:03:46 浏览: 371
可以使用collections模块中的Counter类来统计列表中元素出现的次数,然后使用most_common方法找出出现次数最多的元素。
例如:
```python
from collections import Counter
my_list = [1, 2, 3, 4, 1, 2, 1, 5, 6, 5, 5]
count_dict = Counter(my_list)
most_common = count_dict.most_common(1)
print(most_common[0][0]) # 输出出现次数最多的元素
```
输出结果为:
```
1
```
说明列表中出现次数最多的元素是1。
相关问题
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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)