简体   繁体   English

将预定义的 2d 数组转换为 2d bool 数组

[英]Converting predefined 2d Array into 2d bool array

I am given a predefined array我得到了一个预定义的数组

a = [[2 3 4]
     [5 6 7]
     [8 9 10]]

my issue is converting this array into a boolean array where all even numbers are true.我的问题是将此数组转换为所有偶数都为真的布尔数组。 Any help is appreciated!任何帮助表示赞赏!

I would use numpy, and it's pretty straightforward:我会使用 numpy,它非常简单:

import numpy as np

a = [[2, 3, 4],
     [5, 6, 7],
     [8, 9, 10]]
a = np.asarray(a)
(a % 2) == 0

Do as follows using Numpy:使用 Numpy 执行以下操作:

 import numpy as np a = [[2, 3, 4], [5, 6, 7], [8, 9, 10]] aBool=(np.asarray(a)%2==0)

The variable aBool will contain True where there is an Even value and False for an Odd value.变量 aBool 将包含 True,其中有一个偶数值和 False 一个奇数值。

 array([[ True, False, True], [False, True, False], [ True, False, True]])

This is adapted from the answer found here :这是从这里找到的答案改编的:

a=np.array([1,2,3,4,5,6])

answer = (a[a%2==0])
print(answer)

which is essentially what Andrew said but without using NumPy这基本上就是安德鲁所说的,但没有使用 NumPy

If you're interested in getting booleans and testing for certain conditions within a NumPy array you can find a neat post here如果您有兴趣获取布尔值并测试 NumPy 数组中的某些条件,您可以在此处找到一篇简洁的文章

This can be done simply using one line (if you don't want to use numpy):这可以简单地使用一行来完成(如果你不想使用 numpy):

[[i % 2 == 0 for i in sublist] for sublist in a]

>>> [[True, False, True], [False, True, False], [True, False, True]]

Here, i % 2 denotes the modulus operator, which gives the remainder when the first number is divided by the second.这里, i % 2表示模运算符,它给出第一个数字除以第二个数字时的余数。 In this case, for even numbers i % 2 = 0 , and for odd numbers i % 2 = 1 .在这种情况下,对于偶数i % 2 = 0 ,对于奇数i % 2 = 1 The two = signs means that the expression is evaluated as a boolean.两个 = 符号表示表达式被评估为布尔值。

The two for loops iterate over each list inside of the 2D list.两个for循环遍历 2D 列表中的每个列表。

This can be extended if you find this format easier to understand, but it essentially does the same thing:如果您发现此格式更易于理解,则可以对其进行扩展,但它本质上执行相同的操作:

>>> newlist = []
>>> for sublist in a:
        partial_list = []
        for i in sublist:
                partial_list.append(i % 2 == 0)
        newlist.append(partial_list)


>>> newlist
[[True, False, True], [False, True, False], [True, False, True]]

Why not to mention negations:为什么不提否定:

a = [[2, 3, 4],
     [5, 6, 7],
     [8, 9, 10]]

>>> ~np.array(a)%2
array([[1, 0, 1],
       [0, 1, 0],
       [1, 0, 1]], dtype=int32)

This is a boolean form:这是一个布尔形式:

>>> ~(np.array(a)%2).astype(bool)
array([[ True, False,  True],
       [False,  True, False],
       [ True, False,  True]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM