假设我有以下数组:
[True, True, True, True]
如何切换数组中每个元素的状态?切换将给予我:
[False, False, False, False]
同样,如果我有:
[True, False, False, True]
切换将给予我:
[False, True, True, False]
我知道在Python中切换布尔值最直接的方法是使用“not”,我在stackexchange上找到了一些例子,但我不确定如果它在数组中如何处理。
tyg4sfes1#
使用not仍然是最好的方法。你只需要一个列表解析就可以了:
not
>>> x = [True, True, True, True]>>> [not y for y in x][False, False, False, False] >>> x = [False, True, True, False]>>> [not y for y in x][True, False, False, True]>>>
>>> x = [True, True, True, True]
>>> [not y for y in x]
>>> x = [False, True, True, False]
>>>
我很确定我的第一个解决方案是你想要的。但是,如果你想改变原始数组,你可以这样做:
>>> x = [True, True, True, True]>>> x[:] = [not y for y in x]>>> x[False, False, False, False]>>>
>>> x[:] = [not y for y in x]
>>> x
x3naxklr2#
在纯python中,使用列表解析
>>> x = [True, False, False, True]>>> [not b for b in x][False, True, True, False]
>>> x = [True, False, False, True]
>>> [not b for b in x]
或者,您可以考虑使用numpy数组来实现此功能:
>>> x = np.array(x)>>> ~xarray([False, True, True, False], dtype=bool)
>>> x = np.array(x)
>>> ~x
array([False, True, True, False], dtype=bool)
50pmv0ei3#
@iCodez的列表理解的答案更pythonic。我再加上一种方法:
>>> a = [True, True, True, True]>>> print map(lambda x: not x, a)[False, False, False, False]
>>> a = [True, True, True, True]
>>> print map(lambda x: not x, a)
xggvc2p64#
对于具有多于1个轴的布尔数组,由于二义性,这将导致ValueError。
x = np.logical_not(x)
2023,Python版本3.7.4,numpy版本1.21.6
4条答案
按热度按时间tyg4sfes1#
使用
not
仍然是最好的方法。你只需要一个列表解析就可以了:我很确定我的第一个解决方案是你想要的。但是,如果你想改变原始数组,你可以这样做:
x3naxklr2#
在纯python中,使用列表解析
或者,您可以考虑使用numpy数组来实现此功能:
50pmv0ei3#
@iCodez的列表理解的答案更pythonic。我再加上一种方法:
xggvc2p64#
对于具有多于1个轴的布尔数组,由于二义性,这将导致ValueError。
2023,Python版本3.7.4,numpy版本1.21.6