简体   繁体   中英

Syntax error while trying List comprehension in Python

I am getting a syntax error when trying to change the following code to List comprehension

Initial Code:

new_num =[]
for num in a:
    if num in b:
       if num not in new_num:
          new_num.append(num)
print(new_num)

Change to List comprehension:

new_num = [num for num in a if num in b if num not in new_num]
print(new_num)

I assume you want to extract unique elements from 'a'. If this is what you try to do, the code below does it.

a = [12,4,5,6,7,3,4,12,5,7]
unique_numbers = set(a)
print(unique_numbers)

Output

set([3, 4, 5, 6, 7, 12])

Your code: new_num = [num for num in a if num in b if num not in new_num] does not work for two reasons:

  • You can have only an if statement. You should combine the with a logical operator: if num in b and num not in new_num .
  • You cannot use new_num inside the list comprehesion, as you are not defined it yet, as is the result of the list comprehension you are creating. Even if you correct it as in the previous bullet, it will raise a NameError NameError: name 'new_num2' is not defined .

If you want to use a list comprehension you could use set() .

new_num2 = list(set([num for num in a if num in b]))
print(new_num2)

The list comprehension collects all the elements of a which are in b . set removes duplicates. list converts it back to a list.

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