Simplest way to find the element that occurs the most in each column

后端 未结 4 1241
走了就别回头了
走了就别回头了 2021-01-24 17:51

Suppose I have

data =
[[a, a, c],
 [b, c, c],
 [c, b, b],
 [b, a, c]]

I want to get a list containing the element that occurs the most in each

4条回答
  •  没有蜡笔的小新
    2021-01-24 18:50

    Here's a solution without using the collections module

    def get_most_common(data):
    
        data = zip(*data)
        count_dict = {}
        common = []
        for col in data:
            for val in col:
                count_dict[val] = count_dict.get(val, 0) + 1
            max_count = max([count_dict[key] for key in count_dict])
            common.append(filter(lambda k: count_dict[k] == max_count, count_dict))
    
        return common
    
    if __name__ == "__main__":
    
        data = [['a','a','b'],
                ['b','c','c'],
                ['a','b','b'],
                ['b','a','c']]
    
        print get_most_common(data)
    

提交回复
热议问题