Python 从列表中返回唯一的字符串

use*_*584 0 python list

编写一个函数,将字符串列表作为输入并返回列表中的唯一值。

样本:

>>> unique_list(['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug'])
['cat', 'dog', 'bug', 'ant']
Run Code Online (Sandbox Code Playgroud)

我当前的代码:

def unique_list(input_list):
    for word in input_list:
        if word not in input_list:
            output_list = [word]
            return output_list
    print(output_list)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

> Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    unique_list(['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug'])
  File "/Users/****/Desktop/University/CompSci 101/Lab Work/Lab 05/lab05_Homework.py", line 12, in unique_list
    print(output_list)
UnboundLocalError: local variable 'output_list' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

ssh*_*124 5

你的if说法是从来没有True

那是因为您从列表中获取word,然后检查它是否不在其中。没有意义,因为你获得的唯一方法word就是input_list它是否其中。因此,您output_list永远不会被创建,因此当您尝试打印它时,您会收到局部变量在赋值之前引用的错误'output_list'

但是,我建议获取唯一元素的一种更简单的方法是使用set

>>> print list(set(['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug']))
['cat', 'dog', 'bug', 'ant']
Run Code Online (Sandbox Code Playgroud)

集合是“唯一元素的无序集合”,因此当您将重复元素的列表转换为集合时,它将获得唯一元素,然后您可以将其转换回列表,就像我上面所做的那样打印它list(your_set)

或者,如果这是某种编码实践并且您想坚持使用您的方法,只需output_list在您的方法中添加初始化行,如下所示:

def unique_list(input_list):
    output_list = []
    ... #Rest of your code
Run Code Online (Sandbox Code Playgroud)

澄清:为什么您的代码不起作用(简化示例)

>>> nums = [0,1,2,3,4]
>>> for i in nums:
...     if i not in nums:
...         print 'True'
...     else:
...         print 'False'
False
False
False
False
False
Run Code Online (Sandbox Code Playgroud)