30秒学会 Python 片段 · 2019年6月9日

30秒学会 Python 片段 – most_frequent

Returns the most frequent element in a list.

Use set(list) to get the unique values in the list combined with max() to find the element that has the most appearances.

代码实现

def most_frequent(list):
  return max(set(list), key=list.count)

使用样例

most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]) #2