如何从一个数组得到最重presented对象 [英] How to get the most represented object from an array

查看:164
本文介绍了如何从一个数组得到最重presented对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些对象的数组,有几个对象都是一样的。例如:水果= [苹果,橘子,苹果,香蕉,香蕉,橘子,苹果,苹果]

I have an array with some objects, and there are several objects that are alike. E.g: fruit = [apple, orange, apple, banana, banana, orange, apple, apple]

什么是最有效的方式来获得这个数组psented对象最重$ P $?在这种情况下,这将是苹果,但你将如何走出去,计算出一种有效的方式?

What is the most efficient way to get the most represented object from this array? In this case it would be "apple" but how would you go out and calculate that in an efficient way?

推荐答案

不要推倒重来。在Python 2.7+,您可以使用 Counter类

Don't reinvent the wheel. In Python 2.7+ you can use the Counter class:

import collections
fruit=['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple']
c=collections.Counter(fruit)
print(c.most_common(1))
# [('apple', 4)]

如果你正在使用Python的旧版本,那么你可以下载计数器此处

If you are using an older version of Python, then you can download Counter here.

虽然它的好,知道如何实现这样的事情你自己,这也是一个好主意,习惯使用计数器,因为它是(或将是)标准库的一部分。

While it's good to know how to implement something like this yourself, it's also a good idea to get used to using Counter, since it is (or going to be) part of the standard library.

这篇关于如何从一个数组得到最重presented对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆