[英]Multiple filter using lambda in python on rethinkdb?
I am trying to filter the array object inside a table. 我正在尝试过滤表内的数组对象。 Here is a case where I have filtered and it works perfectly. 在这种情况下,我进行了过滤,效果很好。
tags = ["school", "hollywood"]
tagsLambda = lambda post: (post["tags"].contains(tags[0])) | (post["tags"].contains(tags[1]))
d = r.db("test").table("posts").filter(
tagsLambda
).run()
But, My question is I am doing the lambda operation manually, instead I want tagsLambda
to filter all the tags
. 但是,我的问题是我正在手动执行lambda操作,相反,我希望tagsLambda
过滤所有tags
。 How do I do it? 我该怎么做?
I think you should be able to do something like this: 我认为您应该可以执行以下操作:
tags = ["school", "hollywood"]
r.db("test").table("posts").filter(
lambda post: post["tags"].contains(lambda tag:
r.expr(tags).contains(tag)
)
).run(conn)
See http://rethinkdb.com/api/python/contains/ 参见http://rethinkdb.com/api/python/contains/
tags = ["school", "hollywood"]
tagsLambda = lambda post: (
eval('|'.join(
[r'(post["tags"].contains("' + tag + '"))' for tag in tags]
))
)
d = r.db("test").table("posts").filter(tagsLambda).run()
[ r'post["tags"].contains("' + tag + '")' for tag in tags ]
is a list comprehension. [ r'post["tags"].contains("' + tag + '")' for tag in tags ]
是一个列表[ r'post["tags"].contains("' + tag + '")' for tag in tags ]
。 It builds a list of strings like (post["tags"].contains("school"))
for each tag in tags. 它为标签中的每个标签构建字符串列表,如(post["tags"].contains("school"))
。 The '|'.join
operation builds a string from the list of strings with '|' '|'.join
操作使用'|'从字符串列表中构建一个字符串 in between like (post["tags"].contains("school")) | (post["tags"].contains("hollywood"))
在它们之间(post["tags"].contains("school")) | (post["tags"].contains("hollywood"))
(post["tags"].contains("school")) | (post["tags"].contains("hollywood"))
. (post["tags"].contains("school")) | (post["tags"].contains("hollywood"))
。 eval evaluates the whole string. eval评估整个字符串。
The above code can be simplified using reduce
as 可以使用reduce
as简化以上代码
tags = ["school", "hollywood"]
tagsLambda = lambda post:
reduce(lambda x,y: x | y, [ post["tags"].contains(tag) for tag in tags])
d = r.db("test").table("posts").filter(tagsLambda).run()
For Python 3, 'functools' has to be imported to use reduce
and replace reduce
with functools.reduce
. 对于Python 3,必须导入'functools'才能使用reduce
并用functools.reduce
替换reduce
。
The second lambda can be replaced with a function. 第二个lambda可以替换为一个函数。
import operator as op
reduce(op.or_, [ post["tags"].contains(tag) for tag in tags])
User generators for better result. 用户生成器以获得更好的结果。
reduce(op.or_, ( post["tags"].contains(tag) for tag in tags))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.