Which maximum does Python pick in the case of a tie?

后端 未结 5 1846
盖世英雄少女心
盖世英雄少女心 2020-11-27 16:27

When using the max() function in Python to find the maximum value in a list (or tuple, dict etc.) and there is a tie for maximum value, which one does Python pi

5条回答
  •  旧时难觅i
    2020-11-27 17:01

    From empirical testing, it appears that max() and min() on a list will return the first in the list that matches the max()/min() in the event of a tie:

    >>> test = [(1, "a"), (1, "b"), (2, "c"), (2, "d")]
    >>> max(test, key=lambda x: x[0])
    (2, 'c')
    >>> test = [(1, "a"), (1, "b"), (2, "d"), (2, "c")]
    >>> max(test, key=lambda x: x[0])
    (2, 'd')
    >>> min(test, key=lambda x: x[0])
    (1, 'a')
    >>> test = [(1, "b"), (1, "a"), (2, "d"), (2, "c")]
    >>> min(test, key=lambda x: x[0])
    (1, 'b')
    

    And Jeremy's excellent sleuthing confirms that this is indeed the case.

提交回复
热议问题