简体   繁体   中英

Single expression with .sort() method and slicing on a list

I want to achieve min() , max() by using sorting and slicing on list with numbers. With sorted() function, there are elegant solutions:

maximum = lambda arr: sorted(arr)[-1]

or

def maximum(arr): 
    return sorted(arr)[-1]

But if I want to achieve elegant solution with more memory efficient .sort() method I'm in bottleneck.

Since, .sort() is sorting, without creating new list, and thus returns None , the only one-liner I did is:

def maximum(arr):
    return arr[-1] if arr.sort() == None else "Huston, we found a bug!"

This is not very pythonic. Is there a way for single and elegant expression with .sort() and slicing?

There is probably a way to accomplish what you desired in one line but it is not pythonic. I interestingly think using min() or max() is the more pythonic approach. because it is not only faster and more simple and readable.

if you type import this in your python interpreter you would see "The Zen of Python, by Tim Peters" and it stated:

Simple is better than complex.

and

Readability counts.

I wholeheartedly agree with what J.Doe said, but if you insist on a one-liner, this looks a bit better:

def maximum(arr):
    return arr.sort() or arr[-1]

Since .sort() returns None and None evaluates to False in boolean context, this will always work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM