我编写了一个函数,它接受一个矩阵并查找矩阵中出现次数最多的元素。如果存在多个这样的元素,我的函数将返回所有这些元素的列表。
例如,如果输入是:
matrix = [[0, 5, 1, 1, 0],
[0, 2, 2, 2, 0],
[1, 2, 4, 3, 1]]
结果将是[0, 1, 2]
我的代码如下:
def max_repeat_elem(matrix):
from itertools import chain
if not matrix:
return None
flatten_m = list(chain.from_iterable(matrix))
diction = {}
for i in flatten_m:
occur = flatten_m.count(i)
if occur not in diction:
diction[occur] = [i]
else:
if i not in diction.get(occur):
diction[occur].append(i)
return diction.get(max(diction.keys()))
我认为我的代码可以比现在更便宜。例如。对于重复元素,计数函数会被调用多次。如何降低整个函数的成本(即使使用其他数据结构)?
最佳答案
您可以使用 Counter
来实现此目的,例如:
matrix = [[0, 5, 1, 1, 0],
[0, 2, 2, 2, 0],
[1, 2, 4, 3, 1]]
import itertools
from collections import Counter
counts = Counter(itertools.chain.from_iterable(matrix))
[val for val, count in counts.items() if count == max(counts.values())]
关于python - 返回给定矩阵中出现次数最多的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75328289/