请问如何返回每行中出现次数最多的元素,把它们组成一个列表呢?并且如果0和1出现一样多,就返回0;1和2出现一样多,就返回1. 就比如这个数组: [2 2 2 2 2 2] [1 1 1 2 2 0] [1 1 1 0 0 0] [2 2 2 1 1 1] 我想让他返回 [2] [1] [0] [1] 请问应该如何实现呢?
时间: 2023-12-31 07:06:39 浏览: 21
可以使用Python中的Counter类和条件语句来实现。具体实现步骤如下:
1. 遍历每一行数组,使用Counter类统计每个元素出现的次数。
2. 找到出现次数最多的元素,如果0和1出现一样多,就返回0;1和2出现一样多,就返回1。
3. 将最多出现次数的元素添加到结果列表中。
下面是代码示例:
```python
from collections import Counter
def most_frequent(arr):
result = []
for a in arr:
count = Counter(a)
most_common = count.most_common(1)[0][0]
if most_common == 1 and count[0] == count[1]:
result.append(0)
elif most_common == 2 and count[1] == count[2]:
result.append(1)
else:
result.append(most_common)
return result
arr = [[2, 2, 2, 2, 2, 2], [1, 1, 1, 2, 2, 0], [1, 1, 1, 0, 0, 0], [2, 2, 2, 1, 1, 1]]
print(most_frequent(arr)) # 输出 [2, 1, 0, 1]
```
注意:这里假设每行都存在出现次数最多的元素,如果不存在这样的元素,需要根据具体情况进行修改。