【问题标题】:How to check if two numbers on a 2D array are of different parity如何检查二维数组上的两个数字是否具有不同的奇偶性
【发布时间】:2020-07-01 02:35:01
【问题描述】:

在我的实际情况中,我有一个形状为 (8,2) 的数组,我需要检查两个整数是否具有不同的奇偶性。例如这里我希望第 0 行返回 False(8 和 2 是偶数,所以相同的奇偶性)第 1 行返回 True(10 是偶数,3 是奇数)等等。

[[ 8  2]
[10  3]
[12 1]
[5 6]] 

我希望结果在这样的数组中:

array([ False, True, True, True], dtype=bool)

我想使用 np.all 函数,但我不知道该怎么做。

【问题讨论】:

  • 您能否更具体地说明问题是什么?

标签: python arrays image-processing bit-manipulation parity


【解决方案1】:

您可以sum他们并验证总和是否为偶数:

import numpy as np

a = np.array([[8, 2],
              [10, 3],
              [12, 1],
              [5, 6]])

result = (a.sum(1) % 2).astype(bool)
print(result)

输出

[False  True  True  True]

如果两者的奇偶性相同,则和为偶数,否则为奇数。

【讨论】:

    猜你喜欢
    • 2012-06-13
    • 2010-12-02
    • 2014-05-15
    • 2018-05-06
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    相关资源
    最近更新 更多