简体   繁体   中英

Trying to filter with a lambda function inside of a list comprehension

I am trying to remove all even indices from a list with a list comprehension. I am using a lambda function to filter the even indices, why is it not working?

Input:

data = [e for i, e in enumerate(raw_data) if lambda i: True if i % 2 != 0 else False]

Output:

Input In [90]
data = [e for i, e in enumerate(raw_data) if lambda i: True if i % 2 != 0]
                                             ^
SyntaxError: invalid syntax

The output is returning a syntax error where I defined by lambda. Is it not possible to use a lambda in a list comprehension as the filter argument?

EDIT 1: I know there's no reason to use lambda when I can just put the condition directly into the list comprehension, I'm just curious as to why it didn't work.

EDIT 2: Removed useless numpy code surrounding list comprehension

EDIT 3: Removed return statements from lambda

result = [i for i in range(10) if (lambda i: i%2 == 0)(i)]

Since lambda is an anonymous function, it is still a function. You need to pass value to lambda.

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