【发布时间】:2018-05-22 10:19:22
【问题描述】:
我需要使用下面的语法来过滤列表operations:
a = [ope for ope in operations if ope[0] == 1]
if 语句条件是可变的,可能包含多个条件:
a = [ope for ope in operations if ope[0] == 1 and ope[1] == "test"]
我使用一个函数来构建条件并将其作为字符串返回:
>>>> c = makeCondition(**{"id": 1, "title": 'test'})
>>>> c
"ope[0] == 1 and ope[1] == 'test'"
有没有办法将c 变量集成到列表过滤中?像这样(当然,c 变量在下面的示例中被评估为字符串):
a = [ope for ope in operations if c]
感谢您的帮助!
【问题讨论】:
-
你试过
a = [... if eval(c)]吗? -
为什么将条件构建为字符串?将其设为函数或 lambda 会更有意义。
-
a = [... if eval(c)]确实有效,谢谢@Chris!考虑将您的评论添加为答案,以便我接受。 @tripleee:我不明白你的意思。你能用一个基本的语法例子告诉我更多吗? -
你可以做
conditions[0] = lambda ope : ope[0] == 1等等。将所有条件作为内部 lambda 函数填写一个列表,然后在列表推导中,选择您要与a = [ope for ope in operations if conditions[0](ope)]一起使用的一个条件。 -
让你的函数返回逻辑结果而不是字符串。然后你可以在你的测试中使用它。不要生成大量代码然后使用
evel——几乎永远...
标签: python python-3.x if-statement conditional-statements