请问如何返回每行中出现次数最多的元素,把它们组成一个列表呢?并且如果0和1出现一样多,就返回0;0和2出现一样多,就返回0;1和2出现一样多,就返回1. 就比如这个数组: [2 2 2 0 0 0] [1 1 1 2 2 0] [1 1 1 0 0 0] [2 2 2 1 1 1] 我想让他返回 [0] [1] [0] [1] 请问应该如何实现呢?
时间: 2024-03-24 20:36:18 浏览: 17
可以使用Python中的Counter模块来统计每行中出现次数最多的元素,然后根据要求返回对应的结果。具体实现可以参考下面的代码:
```python
from collections import Counter
def get_max_frequency_elements(arr):
results = []
for row in arr:
counter = Counter(row)
most_common = counter.most_common()
if len(most_common) == 1:
results.append(most_common[0][0])
else:
if most_common[0][1] == most_common[1][1]:
if most_common[0][0] == 0 or most_common[1][0] == 0:
results.append(0)
else:
results.append(1)
else:
results.append(most_common[0][0])
return results
```
这个函数接收一个二维数组作为输入,然后返回一个由每行中出现次数最多的元素组成的列表。对于每行,我们使用Counter模块来统计元素出现的次数,然后通过most_common()方法来获取出现次数最多的元素及其出现次数。如果最常见的元素只有一个,那么就直接将其加入到结果列表中。如果最常见的元素有两个及以上,那么就需要根据要求来决定返回哪个元素。如果0和1出现一样多,就返回0;0和2出现一样多,就返回0;1和2出现一样多,就返回1。最后将所有行的结果组成一个列表并返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)