Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there builtin functions for elementwise boolean operators over boolean lists?

For example, if you have n lists of bools of the same length, then elementwise boolean AND should return another list of that length that has True in those positions where all the input lists have True, and False everywhere else.

It's pretty easy to write, i just would prefer to use a builtin if one exists (for the sake of standardization/readability).

Here's an implementation of elementwise AND:

def eAnd(*args):     return [all(tuple) for tuple in zip(*args)] 

example usage:

>>> eAnd([True, False, True, False, True], [True, True, False, False, True], [True, True, False, False, True]) [True, False, False, False, True] 
like image 917
bshanks Avatar asked May 05 '10 03:05

bshanks


People also ask

Can a Boolean be in a list?

A boolean list ("blist") is a list that has no holes and contains only true and false .

What are the 4 Boolean operators?

Boolean operators are specific words and symbols that you can use to expand or narrow your search parameters when using a database or search engine. The most common Boolean operators are AND, OR, NOT or AND NOT, quotation marks “”, parentheses (), and asterisks *.

What are the 3 Boolean operators in Python?

There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True or False . These operators are and , or , and not and are defined in the table below.

How many Boolean operators Python provides?

However, and and or are so useful that all programming languages have both. There are sixteen possible two-input Boolean operators. Except for and and or , they are rarely needed in practice. Because of this, True , False , not , and , and or are the only built-in Python Boolean operators.


2 Answers

There is not a built-in way to do this. Generally speaking, list comprehensions and the like are how you do elementwise operations in Python.

Numpy does provide this (using &, for technical limitations) in its array type. Numpy arrays usually perform operations elementwise.

like image 180
Mike Graham Avatar answered Sep 23 '22 16:09

Mike Graham


Try:

[ x&y for (x,y) in zip(list_a, list_b)] 
like image 27
ntg Avatar answered Sep 22 '22 16:09

ntg