Python-reduce 函数和 |操作员
我正在查看一些 Web2py 代码。
变量tokens
是某种字符串列表。更准确地说,它被定义为 tokens = form.vars.name.split() ,其中 form.vars.name 是一个字符串。
我的问题涉及以下说明:
query = reduce(lambda a,b:a&b,[User.first_name.contains(k)|User.last_name.contains(k) for k in tokens])
这是我的问题:
我知道
lambda a,b:a&b
定义了a
和b的函数
。什么是a&b
?User.first_name
的contains
方法是否特定于 Web2py ?或者它是否存在于标准 Python 中?User.first_name.contains(k)|User.last_name.contains(k)
中的这个|
运算符是什么?reduce
函数有什么作用?
I am looking at some Web2py code.
The variable tokens
is some kind of a list of strings. To be more precise, it is defined as tokens = form.vars.name.split()
where form.vars.name
is a string.
My question deals with the following instruction :
query = reduce(lambda a,b:a&b,[User.first_name.contains(k)|User.last_name.contains(k) for k in tokens])
Here are my questions :
I know
lambda a,b:a&b
defines a function ofa
andb
. What isa&b
?Is the
contains
method ofUser.first_name
specific to Web2py ? Or does it exist in standard Python ?What is this
|
operator inUser.first_name.contains(k)|User.last_name.contains(k)
?What does the
reduce
function do ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
&
和|
这里不是按位和/或,而是用来构建一个表示数据库查询的特殊对象!它们对应于 SQL 语句中的AND
和OR
&
and|
are not bitwise and/or here, but are used to build a special object that represents a database query! They correspond toAND
andOR
in SQL statements__contains__
的映射,但它确实出现在 Py3k 文档。__contains__
, but it does appear in Py3k docs.&
是按位与运算符。编写代码的人几乎肯定意味着and
,尽管对于布尔值,结果是相同的。.contains()
是web2py提供的方法。a.contains(b)
更 Python 的写法是b in a
。|
是按位或运算符。同样,他们的意思可能是or
。reduce
将作为第一个参数给出的函数应用于第二个参数中的可迭代对象,从左到右,首先使用前 2 个元素,然后使用该计算的结果和第三个元素等。&
is the bitwise and operator. The person writing the code almost certainly meantand
, although for boolean values the result is the same..contains()
is a method provided by web2py.a.contains(b)
is more pythonically written asb in a
.|
is the bitwise OR operator. Again, they probably meantor
.reduce
applies the function given as the first argument to the iterable in the second argument, from left-to-right, first with the first 2 elements, then with the result of that calculation and the third element, etc.