简体   繁体   中英

how could this code Return unique values of a list?

def uniq(list):
    """ Returns unique values of a list """
    u_list = []
    for item in list:
        if item not in u_list:
            u_list.append(item)
    return u_list

A/empty list

B/list with one element (any type)

C/list with 2 different element (same type)

D/list with twice the same element (same type)

E/list with more than 2 times the same element (same type)

F/list with multiple types (integer, string, etc…)

G/not a list argument (ex: passing a dictionary to the method)

uniq = lambda x: list(set(x)) defines a function that should answer most of your needs except what you specify in G . If there are no constraints whatsoever on the input type then it's hard to understand what you're even asking. This will actually work for a dictionary as the set constructor will limit itself to the keys of the dictionary. More generally it will simply iterate over whatever object is passed to it and turn the iteration elements into a set. But I suggest you work on better defining what you mean in G otherwise you may end up with unexpected behavior.

As for how this works, it's quite simple: set(x) turns your list into a set, which automatically removes all duplicates from it, and then list(set(x)) simply turns it back into a list.

Finally, I would highly recommend against naming a function argument list as that is a builtin class, and should not be overridden as a variable name.

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