📌  相关文章
📜  Python|在二维列表的每一列中查找最常见的元素

📅  最后修改于: 2022-05-13 01:54:36.180000             🧑  作者: Mango

Python|在二维列表的每一列中查找最常见的元素

给定一个 2D 列表,编写一个Python程序来查找 2D 列表的每一列中最常见的元素。

例子:

Input : [[1, 1, 3],
        [2, 3, 3],
        [3, 2, 2],
        [2, 1, 3]]
Output : [2, 1, 3]

Input : [['y', 'y'],
         ['y', 'x'],
         ['x', 'x']]
Output : ['y', 'x']

方法#1:使用集合模块中的most_common()

most_common()返回n 个最常见元素的列表及其从最常见到最少的计数。因此,我们可以使用列表推导轻松找到每列中最常见的元素。

# Python3 program to find most common 
# element in each column in a 2D list
from collections import Counter
  
def mostCommon(lst):
          
    return [Counter(col).most_common(1)[0][0] for col in zip(*lst)]
          
# Driver code
lst = [[1, 1, 3],
       [2, 3, 3],
       [3, 2, 2],
       [2, 1, 3]]
print(mostCommon(lst))
输出:
[2, 1, 3]


方法 #3:使用统计模块中的mode()

# Python3 program to find most common 
# element in each column in a 2D list
from scipy.stats import mode
import numpy as np
  
def mostCommon(lst):
      
    val, count = mode(lst, axis = 0)
    return val.ravel().tolist()
          
# Driver code
lst = [[1, 1, 3],
       [2, 3, 3],
       [3, 2, 2],
       [2, 1, 3]]
print(mostCommon(lst))
输出:
[2, 1, 3]