【问题标题】:More Efficient Ways of Returning Most Common Element of a List返回列表中最常见元素的更有效方法
【发布时间】:2021-09-21 01:16:34
【问题描述】:

假设我们有以下代码:

import random
num_samples = 1000
a = list(random.randint(0,9) for _ in range(num_samples))

#sample(a, num_samples if len(a) > num_samples else len(a))
def most_common(lst):
    return max(set(lst), key=lst.count)

most = most_common(a)
print(most)

有没有更快的方法来获取列表中最常见的元素?

【问题讨论】:

标签: python list algorithm


【解决方案1】:

您可以使用Counter(它会为您完成这项工作)

import random
from collections import Counter

num_samples = 1000
a = list(random.randint(0, 9) for _ in range(num_samples))


# sample(a, num_samples if len(a) > num_samples else len(a))
def most_common(lst):
    return max(set(lst), key=lst.count)


most = most_common(a)
print(most)

counter = Counter(a)
print(counter.most_common(1))

【讨论】:

  • 哇,我从来没有见过比使用 max() 更快的方法
  • @balderman:谢谢!如果你得到类似[('"apple"', 200)] 的输出,访问第一个元素"apple" 可能会很麻烦。否则我喜欢这个答案。
  • @Theshape 问题不是用max,其实这里你真的应该用max(counter.items()),会比most_common快,这里的关键是你要避免效率极低 max(a, key=list.count)。在这样的循环中使用 list.count 会迫使您使用二次时间算法,而这应该能够在线性时间内完成(即通过使用计数器)。
猜你喜欢
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2010-12-03
  • 2018-09-27
  • 1970-01-01
相关资源
最近更新 更多