0

I have an array of Django querysets. Django querysets can be merged using the bitwise or operator like this:

n1 = <queryset ...>
n2 = <queryset ...>
merged = n1 | n2

What if I have an array of unspecified size array = [n1, n2, ...] and I'd like to do merged = n1 | n2 | ...?

merged = array[0]
for i in array:
    if (i in array):
        merged = merged | array[i]

Is there a more elegant solution? Something like array.join(|)?

1 Answer 1

3

You can use the operator library to get the operator as a function, and you can use functools.reduce to operate a bunch of items together.

import operator
import functools
merged = functools.reduce(operator.or_, array)

The docs of reduce are nice and concise:

Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

In your case, you have | instead of +, so if you passed it this list, it would calculate ((((1|2)|3)|4)|5). This works the same regardless if the list you pass in has numbers or arbitrary objects. You can also use a lambda to define your function, but operator.or_ is more clear.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.