A safe max() function for empty lists

后端 未结 7 1160
天命终不由人
天命终不由人 2021-02-01 12:28

Evaluating,

max_val = max(a)

will cause the error,

ValueError: max() arg is an empty sequence

Is there a bett

7条回答
  •  猫巷女王i
    2021-02-01 12:53

    In versions of Python older than 3.4 you can use itertools.chain() to add another value to the possibly empty sequence. This will handle any empty iterable but note that it is not precisely the same as supplying the default argument as the extra value is always included:

    >>> from itertools import chain
    >>> max(chain([42], []))
    42
    

    But in Python 3.4, the default is ignored if the sequence isn't empty:

    >>> max([3], default=42)
    3
    

提交回复
热议问题