30秒学会 Python 片段 · 2022年12月8日

30秒学会 Python 片段 – Most frequent element

Returns the most frequent element in a list.

  • Use set() to get the unique values in lst.
  • Use max() to find the element that has the most appearances.

代码实现

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

使用样例

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

翻译自:https://www.30secondsofcode.org/python/s/most-frequent