是否有内置函数可用于布尔列表上的元素布尔运算符? [英] Are there builtin functions for elementwise boolean operators over boolean lists?

查看:95
本文介绍了是否有内置函数可用于布尔列表上的元素布尔运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果您有n个相同长度的布尔变量列表,则逐元素布尔AND应该返回该长度的另一个列表,该列表在所有输入列表都为True的位置上具有True,而在其他所有位置都为False.

这很容易编写,如果存在(出于标准化/可读性的考虑),我只想使用一个内置函数.

这是元素AND的实现:

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

用法示例:

>>> eAnd([True, False, True, False, True], [True, True, False, False, True], [True, True, False, False, True])
[True, False, False, False, True]

解决方案

没有内置的方法可以做到这一点.一般来说,列表理解等是您在Python中进行元素操作的方式.

Numpy确实在其数组类型中提供了此功能(出于技术限制,请使用&). numpy数组通常按元素执行操作.

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]

解决方案

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.

这篇关于是否有内置函数可用于布尔列表上的元素布尔运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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