How can I get the minimum and the maximum element of a list in python

前端 未结 8 1600
执笔经年
执笔经年 2021-01-16 18:06

If a have a list like:

l = [1,2,3,4,5]

and I want to have at the end

min = 1   
max = 5

WITHOUT

8条回答
  •  清酒与你
    2021-01-16 18:16

    If you only require one looping through the list, you could use reduce a (not so) creative way. The helper function could have been reduced as a lambda but I don't do it for sake of readability:

    >>> def f(solutions, item):
    ...     return (item if item < solutions[0] else solutions[0],
    ...             item if item > solutions[1] else solutions[1])
    ... 
    
    >>> L = [i for i in range(5)]
    >>> functools.reduce(f, L, (L[0],L[0]))
    (0, 4)
    

提交回复
热议问题