Gavin
Gavin

Reputation: 1521

how to define filter or expression in string?

If there a way that I can define filter in a variable, then use that variable to filter data frame or filter list?

For example, I can filter the list using code:

l = [1,2,3,4,5]
f = [i for i in l if i > 3]
f

Is there a way that I can define the filter in a variable? (the code below is not working)

ft = repr('if i > 3')
f_repr = [i for i in l eval(ft)] 
f_repr

Upvotes: 2

Views: 305

Answers (4)

Gabriel
Gabriel

Reputation: 1942

Make the entire expression a string then eval it.

l = [1,2,3,4,5]
cond = 'if i > 3'
expr = f'[i for i in l {cond}]'
eval(expr) # => [4, 5]

Upvotes: -1

b-fg
b-fg

Reputation: 4137

Using numpy arrays is quite straightforward

f_repr = f[f>3]

Upvotes: 0

Ashutosh Chapagain
Ashutosh Chapagain

Reputation: 926

You can do that using a lambda function.

ft=lambda i:i>3
f_repr=[i for i in l if ft(i)]
f_repr

Upvotes: 3

Related Questions