为什么我不能在此函数中使用列表理解?

Why can't I use a list comprehension in this function?

我正在解决一个小练习题,程序必须接受用户的单词,直到用户输入一个简单的 space,然后将它们放入一个列表中以删除重复项。我已经找到了如何去做,但我想加入一个列表理解。第一块是工作程序,第二块提供了一个SyntaxError

userinput = None
lst = []
while userinput != " ":
    userinput = input("enter a word: ")
    if userinput not in lst:
        lst.append(userinput)
for word in lst:
    print(word)
userinput = None
lst = []
while userinput != " ":
    userinput = input("enter a word: ")
    [lst.append(userinput) if userinput not in lst] # Here is my comprehension
for word in lst:
    print(word)

列表推导适用于此格式。

[element for element in iterable]

它们本质上是压缩的 for 循环,因此它们需要针对可迭代对象的 forin 语句。

为此目的,如果您只想将逻辑压缩为 1 行,您实际上可以使用 三元运算符

lst.append(userinput) if userinput not in lst else None

列表理解的语法无效 您可以使用列表推导式作为:

[item for item in list]

使用 if 语句

[item for item in list if True]     # with a if statement.

但在您的示例中,您也可以使用

userinput = None
lst = []
while userinput != " ":
    userinput = input("enter a word: ")
    lst.append(userinput)

lst = list(set(lst))

这会将列表更改为一个集合并删除所有重复值

我认为这是一个关于列表理解的有趣话题: https://realpython.com/list-comprehension-python/

Yevhen Kuzmovych 给出的另一个选项是:

userinput = None
lst = set()
while userinput != " ":
    userinput = input("enter a word: ")
    lst.add(userinput)

for word in lst:
    print(word)