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

馋奶兔 提交于 2020-07-02 11:37:11

问题


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]

回答1:


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.




回答2:


Try:

[ x&y for (x,y) in zip(list_a, list_b)]



回答3:


The numpy.all function does what you want, if you specify the dimension to collapse on:

>>> all([[True, False, True, False, True], [True, True, False, False, True], [True, True, False, False, True]], 0)
array([ True, False, False, False,  True], dtype=bool)



回答4:


No, there are no such built-ins. Your method using zip and all / any is what I would use.




回答5:


No, I don't believe there's any such function in the standard library... especially when it's so easy to write in terms of the functions that are provided.



来源:https://stackoverflow.com/questions/2770434/are-there-builtin-functions-for-elementwise-boolean-operators-over-boolean-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!