如何在Python中切换布尔数组?

rjee0c15  于 2023-05-27  发布在  Python
关注(0)|答案(4)|浏览(404)

假设我有以下数组:

  1. [True, True, True, True]

如何切换数组中每个元素的状态?
切换将给予我:

  1. [False, False, False, False]

同样,如果我有:

  1. [True, False, False, True]

切换将给予我:

  1. [False, True, True, False]

我知道在Python中切换布尔值最直接的方法是使用“not”,我在stackexchange上找到了一些例子,但我不确定如果它在数组中如何处理。

tyg4sfes

tyg4sfes1#

使用not仍然是最好的方法。你只需要一个列表解析就可以了:

  1. >>> x = [True, True, True, True]
  2. >>> [not y for y in x]
  3. [False, False, False, False]
  4. >>> x = [False, True, True, False]
  5. >>> [not y for y in x]
  6. [True, False, False, True]
  7. >>>

我很确定我的第一个解决方案是你想要的。但是,如果你想改变原始数组,你可以这样做:

  1. >>> x = [True, True, True, True]
  2. >>> x[:] = [not y for y in x]
  3. >>> x
  4. [False, False, False, False]
  5. >>>
x3naxklr

x3naxklr2#

在纯python中,使用列表解析

  1. >>> x = [True, False, False, True]
  2. >>> [not b for b in x]
  3. [False, True, True, False]

或者,您可以考虑使用numpy数组来实现此功能:

  1. >>> x = np.array(x)
  2. >>> ~x
  3. array([False, True, True, False], dtype=bool)
50pmv0ei

50pmv0ei3#

@iCodez的列表理解的答案更pythonic。我再加上一种方法:

  1. >>> a = [True, True, True, True]
  2. >>> print map(lambda x: not x, a)
  3. [False, False, False, False]
xggvc2p6

xggvc2p64#

对于具有多于1个轴的布尔数组,由于二义性,这将导致ValueError。

  1. x = np.logical_not(x)

2023,Python版本3.7.4,numpy版本1.21.6

相关问题