因为实现很简单, 所以就把代码贴过来:
class P(object): def __init__(self, f): self.f = f def __ror__(self, y): return self.f(y)
使用示例:
In [45]: "423423" | P(int) | P(hex) | P(str.upper)class F(object): '''filter, juge every element is True or False''' def __init__(self, f): self.f = f def __ror__(self, seq): return filter(self.f, seq)
目的: 对一个list进行过滤, 先取出大于2的数值, 再取出偶数
a=[1,2,3,4,5] def dayu2(x): return x>2 def oushu(x): return x % 2==0 #print a|F(lambda x:x>2)|F(lambda x:x % 2==0) print a|F(dayu2)|F(oushu)
最后得到[4]
"123456789".replace('1','2').replace('2','3')
适用情况:执行更复杂的查询(比如,实现筛选条件的 OR、AND 关系)
例子:
models如下:
class Article(models.Model): headline = models.CharField(max_length=50) pub_date = models.DateTimeField()
想查询headline字段开头以'hello',或者结尾以'Goodbye'的数据。
代码实现:
Article.objects.filter(Q(headline__startswith='Hello') | Q(headline__startswith='Goodbye'))
Article.objects.filter(~Q(pk=self.a1) & ~Q(pk=self.a2))
# 位于/django/db/models/query_utils.py class Q(tree.Node): """ Encapsulates filters as objects that can then be combined logically (using & and |). """ # Connection types AND = 'AND' OR = 'OR' default = AND def __init__(self, *args, **kwargs): super(Q, self).__init__(children=list(args) + kwargs.items()) def _combine(self, other, conn): if not isinstance(other, Q): raise TypeError(other) obj = type(self)() obj.add(self, conn) obj.add(other, conn) return obj def __or__(self, other): return self._combine(other, self.OR) def __and__(self, other): return self._combine(other, self.AND) def __invert__(self): obj = type(self)() obj.add(self, self.AND) obj.negate() return obj