美文网首页Python
python之max使用技巧

python之max使用技巧

作者: heheddff | 来源:发表于2018-11-30 11:07 被阅读0次

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.

相关文章

  • python之max使用技巧

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

  • Python基本数据类型

    Python补充02 Python小技巧 在这里列举一些我使用Python时积累的小技巧。这些技巧是我在使用Pyt...

  • python的小技巧之min,max

    在限制某个值的大小时候,最早是这样写的: 后来学会了更好的写法 但是今天偶尔检查自己代码的时候,突然发现,既然是数...

  • python自动化办公:玩转word之页眉页脚秘笈

    节将就python操作word的页眉页脚技巧做深入介绍。 使用页眉和页脚 python操作word的页眉页脚技巧做...

  • Excel技巧之MAX函数

    说明返回一组值中的最大值。 语法MAX(number1, [number2], ...) MAX 函数语法具有下列...

  • 59个Python使用技巧,从此你的Python与众不同!

    今天给大家分享几个Python使用的小技巧,原文来自于Python 技巧总结,进行了细微的调整,感谢作者! 1. ...

  • python爬虫小技巧

    Python基本数据类型 同步滚动:关 Python补充02 Python小技巧 在这里列举一些我使用Python...

  • python使用技巧

    运行调试等: http://blog.csdn.net/u013088062/article/details/50...

  • python使用技巧

    1 使用colorama库带颜色输出日志 2 pwn awd模板 awd模式千万不要使得单个脚本功能太过庞大,脚本...

  • Python使用技巧

    包 from netCDF4 import Dataset,num2dateimport datetimeimpo...

网友评论

    本文标题:python之max使用技巧

    本文链接:https://www.haomeiwen.com/subject/urmccqtx.html