python,找出列表中出现次数最多的元素,并单独输出
时间: 2024-05-09 14:17:00 浏览: 14
可以使用 Python 的 Counter 模块来实现,代码如下:
```python
from collections import Counter
lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
counter = Counter(lst)
most_common = counter.most_common(1)
print(most_common[0][0])
```
输出为:
```
5
```
相关问题
python怎么找出列表中出现次数最多的数
在 Python 中,可以使用 collections 模块中的 Counter 类来统计列表中每个元素出现的次数,然后使用 most_common() 方法找出出现次数最多的元素和它的出现次数。
下面是一个示例代码:
```python
from collections import Counter
my_list = [1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1]
counter = Counter(my_list)
most_common = counter.most_common(1)
print(most_common[0][0])
```
运行结果:
```
1
```
这个示例中,my_list 是一个包含了一些整数的列表,我们使用 Counter 类来统计每个元素出现的次数,然后使用 most_common() 方法找出出现次数最多的元素和它的出现次数。由于我们只需要找出出现次数最多的元素,因此将 most_common() 方法的参数设置为 1。最后,使用 print() 函数打印出出现次数最多的元素。
在python中怎么找出列表中出现次数最多的数
在Python中,可以使用collections模块中的Counter函数来统计列表中每个元素出现的次数,并使用most_common()函数返回出现次数最多的元素和它的出现次数。具体实现如下:
```python
from collections import Counter
my_list = [1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1]
counter = Counter(my_list)
most_common = counter.most_common(1)
print(most_common[0][0])
```
输出结果为:
```
1
```
表示列表中出现次数最多的数是1。
相关推荐
![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)