Matt
Matt

Reputation: 161

Appending series elements of a list using the "bitwise or" operator

Basically I have a list where each element is a series and the list is arbitrarily long. I would like to know how to iterate through the list in such a way that I can create a variable matches = listerino[0] | listerino[1] | ... | listerino[len(listerino)].

So far the closest I have come to anything like the above is:

matches = pd.Series()       
for t in range(0, len(listerino)-1, 2):
      x = listerino[t] | listerino[t+1]
      matches = matches | x

However, as you can probably see, this will only work the way I want it for an even length list as it misses off the last element for odd length lists. Also, I've had to messily define matches to first be equal to an empty series and then append on x, is there a better way of doing this?

Thanks

Upvotes: 0

Views: 82

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43276

This operation you're trying to perform is commonly called a "reduction", and can be done with functools.reduce:

import functools
import operator

matches = functools.reduce(operator.or_, listerino)

The operator module conveniently defines the operator.or_ function, which takes two inputs and returns x | y.

Upvotes: 3

TayTay
TayTay

Reputation: 7170

Why not use the |= operator?

matches = None
for series in listerino:
    # base case:
    if matches is None:
        matches = series
    else:
        matches |= series

This is equivalent to matches = matches | series

Upvotes: 1

Related Questions