How to return the maximum element of a list in Python?

旧巷老猫 提交于 2019-12-11 03:10:20

问题


I am trying to simplify this function at his maximum, how can I do?

def eleMax(items, start=0, end=None):
    if end is None:
        end = len(items)
    return max(items[start:end])

I though of

def eleMax(items, start=0, end=-1):
    return max(items[start:end])

But the last element is deleted from the list.

Thank for your help.


回答1:


You can just remove these two lines:

if end is None:
    end = len(items)

The function will work exactly the same:

>>> a=[5,4,3,2,1]
>>> def eleMax(items, start=0, end=None):
...     return max(items[start:end])
...
>>> eleMax(a,2)   # a[2:] == [3,2,1]
3



回答2:


Just use max(items).

Python ranges are 'half-open'. When you slice a list in Python with [start:end] syntax, the start is included and the end is omitted.




回答3:


def eleMax(items, start=None, end=None):
    return max(items[slice(start, end)])



回答4:


When operating over large lists or many calls to this you can avoid the overhead of the slice creating a new list and copying the pointers.

http://docs.python.org/library/itertools.html#itertools.islice

Itertools contains islice which allows for iterating over the list in place without actually returning a new list for the slice.

from itertools import islice

def eleMax(items, start=None, end=None):
    return max(itertools.islice(items, start, end))

One current limitation is that negative values are not allowed for start, end, step.



来源:https://stackoverflow.com/questions/3892957/how-to-return-the-maximum-element-of-a-list-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!