简体   繁体   中英

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

I am working on a little practice problem where the program must accept words from the user until the user enters a simple space, and put them in a list removing duplicates. I have found out how to do it but I would like to incorporate a list comprehension. The first block is the working program, the second provides a 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)

The syntax of the list comprehensions is invalid you can use a list comprehensions as:

[item for item in list]

with an if statement

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

but in your example you can also use

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

lst = list(set(lst))

this wil change the list to an set and remove all duplicated values

I think this is an ineteresting topic about list-comprehension: https://realpython.com/list-comprehension-python/

another option with set given by Yevhen Kuzmovych is:

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

for word in lst:
    print(word)

List comprehensions work with this for format.

[element for element in iterable]

They are essentially condensed for loops so they require both for and in statements against an iterable.

For this purpose you could actually use a ternary operator if you just want to condense the logic to 1 line

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

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