[转载] Python内置函数-min函数和max函数-详解

参考链接: Python min()

博文主要内容如下: 

 

 max和min函数的使用介绍: 

 对可迭代对象元素进行比较,找到最大/最小值      max(iterable, *[, default=obj, key=func])对传入的多个参数进行比较,找到最大/最小值      max(arg1, arg2, *args, *[, key=func])介绍对复杂结构的数据下,如何使用函数定义中的key  。

          需求: 找到列表中出现次数最多的元素。          三种实现方式:              (1)灵活使用max函数的key参数 ;              (2)使用字典统计元素计数,手工实现封装成函数  ;              (3)拓展讲解了 collections.Counter类 ,使用Counter对象的most_common方法。 

 拓展内容:heapq模块的nlargest函数部分源码、 collections.Counter类介绍以及  most_common方法源码。 

 

 

如何去探索max和min函数的功能呢?我们首先要做的就是阅读函数的官方API了!    使用IDE查看函数,或者是在交互式环境下输入命令: help(max),会给出官方的函数注释: 

def max(*args, key=None): # known special case of max

    """

    max(iterable, *[, default=obj, key=func]) -> value

    max(arg1, arg2, *args, *[, key=func]) -> value

    

    With a single iterable argument, return its biggest item. The

    default keyword-only argument specifies an object to return if

    the provided iterable is empty.

    With two or more arguments, return the largest argument.

    """

    pass

 

def min(*args, key=None): # known special case of min

    """

    min(iterable, *[, default=obj, key=func]) -> value

    min(arg1, arg2, *args, *[, key=func]) -> value

    

    With a single iterable argument, return its smallest item. The

    default keyword-only argument specifies an object to return if

    the provided iterable is empty.

    With two or more arguments, return the smallest argument.

    """

    pass 

显示这样的内容,一般来说就代表了这两个函数的底层实现是C语言程序。有关具体的实现方法还需要进一步的探索源码。这篇博文我们先掌握API的内容:          从函数说明上来看。max和min函数的使用方法是一样的,区别仅在于max函数是找最大值,min函数是找最小值。下面仅以max函数作为示例对max和min函数的使用进行说明: 

 

 注意,使用min和max,相互比较的元素之间必须是可比较的,否则会提示错误;有关元素之间的比较,我在之前一篇文章中展开了讨论,这篇博文的最后一部分是有关元素之间比较的讨论。博文地址:数据类型-容器类数据类型 

 

 一、函数的两种使用方式:1,max(iterable, *[, default=obj, key=func]) -> value       iterable:  要比较的元素都在可迭代对象中,第一个位置参数传入这份可迭代对象,函数将返回可迭代对象中最大的元素。  如果传入的是字典,那么将比较的是字典的键,也就是相当于传入了dt.keys()。 

# 生成一个打乱顺序的由0-9数字组成的列表,用来测试max和min函数

>>> from random import shuffle

>>> data = list(range(10))

>>> shuffle(data)

 

>>> max(data)

9

>>> min(data)

    关键字参数default:   当可迭代对象中没有元素,如果指定了default关键字参数,那么就返回default参数的值。这种情况如果没有指定default参数,程序会报错:ValueError: max() arg is an empty sequence; 

>>> max(range(10))

9

>>> max(range(0))

Traceback (most recent call last):

  File "", line 1, in

ValueError: max() arg is an empty sequence 

下面的一段代码是我在阅读heapq模块的nlargest函数的源码时遇到的有关 default关键字参数的使用:   

def nlargest(n, iterable, key=None):

    """找到数据集中最大的n个元素

    函数作用等值于:  sorted(iterable, key=key, reverse=True)[:n]

    """

    # Short-cut for n==1 is to use max()

    if n == 1:

        it = iter(iterable)

        sentinel = object()

        if key is None:

            result = max(it, default=sentinel)

        else:

            result = max(it, default=sentinel, key=key)

        return [] if result is sentinel else [result]

    pass

# 注意:sentinel是哨兵位置,用来监测传入的数据集是不是空的。

# 这里就是利用了max函数的default参数的作用来设置的哨兵位置,在可迭代对象为空的情况下能够返回空列表[] 

2,max(arg1, arg2, *args, *[, key=func]) -> value     传入多个参数,多个参数之间进行比较,找到最大的那个参数。 

>>> max(9, 1, 2, 3)

二、函数的缺省参数key的使用: key应当传入一个可调用对象,一般传入的是函数。指定key之后,max函数就会根据key处理后的元素进行比较。 

需求1: 比如下面的情况,每种水果的价格信息都是以字典的形式存放的列表中,要找到最贵的水果和最便宜的水果 

fruit_shop = [

    {'name': 'apple',  'price': 5.68},

    {'name': 'orange', 'price': 4.22},

    {'name': 'banana', 'price': 2.65},

    {'name': 'berries', 'price': 10.75}]

 

cheap = min(fruit_shop, key=lambda s: s['price'])

expensive = max(fruit_shop, key=lambda s: s['price'])

print('最便宜的水果是:', cheap)

print('最贵的水果是:', expensive)

 

####

# 最便宜的水果是: {'name': 'banana', 'price': 2.65}

# 最贵的水果是: {'name': 'berries', 'price': 10.75} 

需求2:找到列表中出现次数最多的元素。 

>>> lt = [2, 2, 3, 1, 2, 2, 1, 8, 5]

>>> max(set(lt), key=lt.count)

 

 注:将count方法作为参数传递给max函数,则在此max函数是对元素出现频次进行比较的。 

 1.set(lt) 能够得到lt列表中所有唯一值,简单地说就是给列表元素去重,得到的是一个集合(即set类型) 

 >>> set(lt)

 

{1, 2, 3, 5, 8} 

 2.列表的count方法是找到统计列表元素出现的次数 

 >>> lt.count(2)

4

>>> lt.count(1)

 

  

不使用max函数我们要如何实现呢? 

 第一种方式: 自定义函数,手动的使用字典去统计元素计数 

# 使用字典dt,统计元素(key)以及元素出现的次数(value) # 出现次数最大的元素用max_count_key存放, # 遍历列表元素,如果字典中已经统计过该元素的出现次数,那么不再重复进行统计;                 否则使用列表的count方法统计元素出现次数,并与max_count_key比较 

def max_count(lt):

    dt = {}

    max_count_key = None

    for i in lt:

        # 字典中已经存在的元素不再进行统计

        if i not in dt:

            count = lt.count(i)

            dt[i] = count

            if count > dt.get(max_count_key, 0):

                max_count_key= i

    return max_count_key 

 第二种方式(推荐):使用collections.Counter类,它的most_common() 方法就是查找到序列中出现次数最多的 

collections.Counter类,对可迭代对象中的元素进行计数,并以键值对的形式保存在Counter对象中 Counter对象属于映射,能够通过dict()将Counter对象转换为字典。 

>>> from collections import Counter

>>> c = Counter('MyNameisMarsenHelloWorld')

>>> c

Counter({'e': 3, 'l': 3, 'M': 2, 'a': 2, 's': 2, 'r': 2, 'o': 2, 'y': 1, 'N': 1, 'm': 1, 'i': 1, 'n': 1, 'H': 1, 'W': 1, 'd': 1})

>>> dict(c)

{'M': 2, 'y': 1, 'N': 1, 'a': 2, 'm': 1, 'e': 3, 'i': 1, 's': 2, 'r': 2, 'n': 1, 'H': 1, 'l': 3, 'o': 2, 'W': 1, 'd': 1} 

Counter类的most_common(n=None) 方法:列出n个最常见的元素及其计数,从最常见到最少见。如果n为None,则列出所有元素计数。也是从最常见到最少见。 函数返回值是由结果元素的组成的列表。 

>>> c.most_common()

[('e', 3), ('l', 3), ('M', 2), ('a', 2), ('s', 2), ('r', 2), ('o', 2), ('y', 1), ('N', 1), ('m', 1), ('i', 1), ('n', 1), ('H', 1), ('W', 1), ('d', 1)]

>>> c.most_common(3)

[('e', 3), ('l', 3), ('M', 2)] 

most_common方法源码阅读: # 当n==None时, 方法的实现是通过内置函数: sorted(iterable [, key=None [,reverse=False]]) 对元素计数的统计结果进行逆序排序。 # 当方法的调用指定n的值时, 方法的实现是通过heapq模块的nlargest(n, iterable [ , key=None ])函数实现的,上面提到过这个函数的作用是从可迭代对象中找到最大的n个元素。直接利用这个函数,只需要用元素的计数进行比较,这样得到   了最常见的n个元素了。 

def most_common(self, n=None):

    if n is None:

        return sorted(self.items(), key=_itemgetter(1), reverse=True)

    return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) 

了解到Counter类之后,它在对数据技术的场合下是非常方便使用的工具,我们可以优先选择使用Counter类来实现功能,这比我们手工的使用字典计数方便很多。 

对于这个需求2:找最大出现次数或者最小出现次数的元素时直接使用max或者min函数解决即可 

如果需求是想找最常见的n个元素,那么就优先选择Counter类去实现相关功能。 

>>> lt = [2, 2, 3, 1, 2, 2, 1, 8, 5]

>>> Counter(lt).most_common(1)

[(2, 4)]

>>> Counter(lt).most_common(1)[0][0]

2

你可能感兴趣的:([转载] Python内置函数-min函数和max函数-详解)