How to make a string interpreted as a condition with Python?

落花浮王杯 提交于 2020-01-06 06:10:13

问题


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 conditions:

a = [ope for ope in operations if ope[0] == 1 and ope[1] == "test"]

I use a function to build the condition and return it as a string:

>>>> c = makeCondition(**{"id": 1, "title": 'test'})
>>>> c
"ope[0] == 1 and ope[1] == 'test'"

Is there a way to integrate the c variable into the list filtering? Something like this (of course, the c variable is evaluated as a string in the below example):

 a = [ope for ope in operations if c]

Thanks for help!


回答1:


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




回答2:


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

def mult3(n):
    return n % 3 == 0

def mult7(n):
    return n % 7 == 0

def mult3_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.



来源:https://stackoverflow.com/questions/47709795/how-to-make-a-string-interpreted-as-a-condition-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!