【问题标题】:Python Return Most Common Element [duplicate]Python返回最常见的元素[重复]
【发布时间】:2019-03-06 02:30:16
【问题描述】:

我正在尝试创建一个函数,该函数从传递的数组中返回最常见的元素。我的代码如下所示:

def get_classification(classes):
    from collections import Counter
    count = Counter(classes)
    return count.most_common()[0]

它正确地返回了最常见的元素。但是,它以element, count 的格式返回它,例如:


3.0, 2
2.0, 3
1.0, 3

我不希望它返回那个元组。我只是需要它来返回最常见的元素。这怎么可能?

我已经尝试了解决方案:

counts = numpy.bincount(classes)
final = numpy.argmax(counts)

return final

但这对我也不起作用。 任何建议将不胜感激。

【问题讨论】:

  • 第二种方案更简单,向下滚动查看
  • 我无法让该解决方案为我工作,即使花了半个小时。 @U9-转发
  • 使用:max(set(classes), key=classes.count)
  • 明白了,我再试试,谢谢。很抱歉重复,我确实看到了那个帖子并尝试过,但无济于事@U9-Forward

标签: python arrays python-3.x


【解决方案1】:

您可以再次使用索引来获取元组的第一个元素:

def get_classification(classes):
    from collections import Counter
    count = Counter(classes)
    return count.most_common()[0][0]

print(get_classification([1, 3, 3, 1, 2, 1])) # ==> 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2021-09-21
    • 1970-01-01
    • 2017-01-05
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多