python之max使用技巧

max获取最大值时,若给定的值如果为空,且未给max初始默认值,max会抛出异常

a = []
max(a)

抛出的异常

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-31-7369ceda7e26> in <module>
      1 a = []
----> 2 max(a)

ValueError: max() arg is an empty sequence

未防止max抛出异常,可指定默认值

a = []
max(a,default=False)

结果为False

False

官方说明

max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] andheapq.nlargest(1, iterable, key=keyfunc).

New in version 3.4: The default keyword-only argument.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,442评论 0 9
  • 一、Java 简介 Java是由Sun Microsystems公司于1995年5月推出的Java面向对象程序设计...
    子非鱼_t_阅读 4,262评论 1 44
  • 归来,我们就着照片谈论铁炉峁,照片空翠欲滴,照片里的人笑容可掬,惹得未去的朋友艳羡不已。 我们一起谈论铁炉峁,谈论...
    瞻子苏阅读 177评论 0 0
  • 凋残的风里 有个不平凡的灵魂 刚毅的侧脸 写着你的坚定与从容 是你 我们的人生多了份勇敢
    枫叶子飘飘阅读 143评论 0 0