简体   繁体   中英

Can anybody explain to me how this sorted work?

I found this edabit challenge ( link to challenge ):

Create a function that takes a list of numbers lst, a string s and return a list of numbers as per the following rules:

"Asc" returns a sorted list in ascending order. "Des" returns a sorted list in descending order. "None" returns a list without any modification.

Some person Evgeny SH propose this solution:

def asc_des_none(lst, s):
    return sorted(lst, reverse=s == 'Des') if s else lst

Can you explain me how sorted(...) part works? Thanks in advance!

sorted() returns a sorted copy of the list.

The function could be spelled out as

def asc_des_none(lst, s):
    if s:
        if s == "Des":
            return sorted(lst, reverse=True) 
        return sorted(lst, reverse=False) 
    return lst

Strictly speaking it doesn't do what the spec says, as it will return the list in ascending order if s is anything but a falsy value.

To be strictly compliant with the spec, it should be something like

def asc_des_none(lst, s):
    if s == "Des":
        return sorted(lst, reverse=True) 
    if s == "Asc":
        return sorted(lst, reverse=False) 
    if s is None:
        return lst
    raise ValueError(f"`s` must be Asc, Des, or None; not {s!r}")

or similar.

def asc_des_none(lst, s):
    return sorted(lst, reverse=s == 'Des') if s else lst

The sorted function sorts an iterable (eg a list) and outputs a sorted copy. It can take a reverse parameter, set to True or False . If True if will output the list sorted in descending order.

So, if s == "Desc" , the list will be sorted in descending order.

The other part … if s else lst will run is s is truthy, else will output the unchanged lst. Truthy objects are non null numbers, non empty strings, not None.

I think your friend wanted to use the fact that None is falsy, but here as we actually have "None" this wouldn't work.

If really the "None" string should trigger no change, the correct code should be:

def asc_des_none(lst, s):
    return sorted(lst, reverse=s == 'Des') if s !="None" else lst

The goal is to produce a Boolean value indicating if the list should be sorted in reverse (when s == 'Des' ) or not (when s != 'Des' ), or if the list should not be sorted at all.

I'd be a little stricter in how s is handled. I'll allow three possible values: any other value produces a ValueError .

def asc_des_none(lst, s):
    if s is None:
        return lst

    try:
        rev = {'Asc': False, 'Des': True}[s]
    except KeyError:
        raise ValueError(f"Unrecognized sorting direction '{s}'")

    return sorted(lst, reverse=rev)

The syntax of sorted function is

sorted(iterable, key=None, reverse=False)

where iterable is our lst. The other parameter reverse which is False by default sorts the lst in ascending order but if reverse is given a value of True our sorted function sorts the lst in descending order, In reverse=s == 'Des' , s == 'Des' evaluates to true if the value of s is Des which in turn sorts our lst in descending order.

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