python - 返回给定矩阵中出现次数最多的元素

标签 python python-3.x

我编写了一个函数,它接受一个矩阵并查找矩阵中出现次数最多的元素。如果存在多个这样的元素,我的函数将返回所有这些元素的列表。

例如,如果输入是:

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/

相关文章:

python - 在Python中读取目录和子目录中的所有文件

python - 关键字参数解包要求

python - 为什么没有引发 ValueError ?

python - 仅从标签 BeautifulSoup Python 获取直接文本

具有多个参数的 python getattr()

python - 使用 TLS1.1 和 urllib3 的 HTTP GET 站点

python - BeautifulSoup soup.select 切断子标签

python - TextBlob NaiveBayesAnalyzer 极慢(与 Pattern 相比)

python - 如何在 Gtk 对话框中显示视频?

python - 如何打印格式指数