Python列表按位操作 [英] Python list to bitwise operations

查看:359
本文介绍了Python列表按位操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获取django查询表达式的列表(例如 Q(first_name =Jordan),其中 Q django.db.models.Q )和按位或它们在一起?



换句话说我有这样的东西:

  search_string =各种搜索词
/ pre>

我想这样做:

  search_params = [Q(description__icontains = term)for re.split(r'\W',search_string)] 
search_params = something_magical(search_params)
results = Record.objects.filter(search_params)

其中 search_params 现在相当于 Q(description__icontains =各种)| Q(description__icontains =search| Q(description__icontains =terms



我知道这可能是这样的功能: / p>

  def something_magical(lst):
result = lst [0]
for l in lst [1: ]
result | = l
return result

所以我想知道这个功能已经在Python中构建了(我假设它比我的函数更优化)。



尽管我对这个应用感兴趣, m / p>

解决方案

你可能想要



<$ python 3
search_params = reduce(operator.or_,search_params,Q())

这将会在< | code> search_params ,从空的条件开始 Q()


Is there a way to take a list of django query expresses (e.g. Q(first_name="Jordan"), where Q is django.db.models.Q) and bitwise OR them together?

In other words, I have something like this:

search_string = "various search terms"

And I want to do this:

search_params = [Q(description__icontains=term) for term in re.split(r'\W', search_string)]
search_params = something_magical(search_params)
results = Record.objects.filter(search_params)

where search_params now is equivalent to Q(description__icontains="various") | Q(description__icontains="search" | Q(description__icontains="terms"

I know it would be possible with a function like this:

def something_magical(lst):
    result = lst[0]
    for l in lst[1:]
        result |= l
    return result

So I'm wondering if this functionality is already built into Python (and I'm assuming it's more optimized than my function here).

Although I'm interested in it for this application, I'm also just interested in it theoretically.

解决方案

You probably want

import operator 
from functools import reduce    # Python 3
search_params = reduce(operator.or_, search_params, Q())

This will place a bit-wise or (|) between all the items in search_params, starting with an empty condition Q().

这篇关于Python列表按位操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆