开发者

Python - reduce function and | operator

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 :

  1. I know lambda a,b:a&b defines a function of a and b. What is a&b ?

  2. Is the contains method of User.first_name specific to Web2py ? Or does it exist in standard Python ?

  3. What 开发者_如何学Cis this | operator in User.first_name.contains(k)|User.last_name.contains(k) ?

  4. What does the reduce function do ?


  1. In Web2Py & and | are not bitwise and/or here, but are used to build a special object that represents a database query! They correspond to AND and OR in SQL statements
  2. contains is part of Web2Pys DAL
  3. See 1.
  4. reduce is fold, a very fundamental higher order function that essentially reduces a list to a result, using the function given.


  1. Bitwise and.
  2. I believe contains, in that context is more-or-less a mapping to __contains__, but it does appear in Py3k docs.
  3. Bitwise or.
  4. reduce iterates through an iterable object (param 2) and calls the passed function (param 1) on all of the elements. It returns the aggregate value.


  1. & is the bitwise and operator. The person writing the code almost certainly meant and, although for boolean values the result is the same.

  2. .contains() is a method provided by web2py. a.contains(b) is more pythonically written as b in a.

  3. | is the bitwise OR operator. Again, they probably meant or.

  4. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜