简体   繁体   English

此代码如何返回列表的唯一值?

[英]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 A/空列表

B/list with one element (any type) B/list 有一个元素(任何类型)

C/list with 2 different element (same type)具有 2 个不同元素(相同类型)的 C/list

D/list with twice the same element (same type)具有两次相同元素(相同类型)的 D/list

E/list with more than 2 times the same element (same type)具有超过 2 次相同元素(相同类型)的 E/list

F/list with multiple types (integer, string, etc…)具有多种类型(整数、字符串等)的 F/list

G/not a list argument (ex: passing a dictionary to the method) G/不是列表参数(例如:将字典传递给方法)

uniq = lambda x: list(set(x)) defines a function that should answer most of your needs except what you specify in G . uniq = lambda x: list(set(x))定义了一个 function ,它应该满足您的大部分需求,除了您在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.这实际上适用于字典,因为 set 构造函数会将自身限制为字典的键。 More generally it will simply iterate over whatever object is passed to it and turn the iteration elements into a set.更一般地说,它将简单地迭代传递给它的任何 object 并将迭代元素转换为一个集合。 But I suggest you work on better defining what you mean in G otherwise you may end up with unexpected behavior.但我建议您努力更好地定义G中的含义,否则您可能最终会出现意外行为。

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.至于它是如何工作的,这很简单: set(x)将您的列表转换为一个集合,它会自动从中删除所有重复项,然后list(set(x))将其简单地转换回一个列表。

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.最后,我强烈建议不要将 function 参数list命名为内置 class,并且不应将其作为变量名覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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