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

后端 未结 4 1202
走了就别回头了
走了就别回头了 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:33

    Use a list comprehension plus collections.Counter():

    from collections import Counter
    
    [Counter(col).most_common(1)[0][0] for col in zip(*data)]
    

    zip(*data) rearranges your list of lists to become a list of columns instead. Counter() objects count how often anything appears in the input sequence, and .most_common(1) gives us the most popular element (plus it's count).

    Provided your input is single character strings, that gives:

    >>> [Counter(col).most_common(1)[0][0] for col in zip(*data)]
    ['b', 'a', 'c']
    

提交回复
热议问题