如何使用Python将字符串解释为条件? [英] How to make a string interpreted as a condition with Python?
本文介绍了如何使用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 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'"
有没有办法将 c
变量集成到列表过滤中?这样的事情(当然, c
变量在下面的示例中被评估为字符串):
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]
谢谢帮助!
推荐答案
如评论所述,如果要将字符串更改为表达式,可以使用 eval(string)
。
As commented, if you want to change the string to be considered as an expression, you can use eval(string)
.
这篇关于如何使用Python将字符串解释为条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文