Skip to content Skip to sidebar Skip to footer

How To Make A String Interpreted As A Condition With Python?

I need to use the following syntax to filter the list operations: a = [ope for ope in operations if ope[0] == 1] The if statement condition is variable and may contain multiple co

Solution 1:

eval is considered unsafe and is generally avoided.

You can use [filter][1] with functions. For this you should put your test conditions in a function.

Here's an example to create a list of numbers between 1 and 100 that are multiples of 3 and 7

defmult3(n):
    return n % 3 == 0defmult7(n):
    return n % 7 == 0defmult3_and_7(n):
    return mult3(n) and mult7(n)

list(filter(mult3_and_7, range(1, 101)))

A more consice way is to use lambdas:

list(filter(lambda n: (n % 3 == 0) and (n % 7 == 0), range(1, 101))

The cool thing is you can chain filters like so:

list(filter(lambda n: n % 3 == 0, filter(lambda n: n % 7 == 0, range(1, 101))))

They all give [21, 42, 63, 84]

This approach should help you chain multiple conditions clearly.

Solution 2:

As commented, if you want to change the string to be considered as an expression, you can use eval(string).

Post a Comment for "How To Make A String Interpreted As A Condition With Python?"