在列表Python中翻转布尔值

我在Python中有一个布尔列表

mylist  = [True , True, False,...]

我想改为逻辑相反的[False, False, True , ...]有没有一种内置的方法可以在Python中执行此操作(类似于调用not(mylist)),而无需使用手写循环来反转元素?

smilingbuddha asked 2020-01-23T15:53:29Z
8个解决方案
62 votes

列表理解很容易:

mylist  = [True , True, False]

[not i for i in mylist]

产量

[False, False, True]
Levon answered 2020-01-23T15:53:47Z
30 votes

一元波浪号(〜)将对numpy.ndarray执行此操作。 所以:

>>> import numpy
>>> mylist = [True, True, False]
>>> ~numpy.array(mylist)
array([False, False, True], dtype=bool)
>>> list(~numpy.array(mylist))
[False, False, True]

请注意,翻转列表的元素将为numpy.bool_类型,而不是bool。

Steven Matz answered 2020-01-23T15:54:11Z
11 votes
>>> import operator
>>> mylist  = [True , True, False]
>>> map(operator.not_, mylist)
[False, False, True]
John La Rooy answered 2020-01-23T15:54:27Z
8 votes

Numpy明确包含此功能。 功能“ numpy.logical_not(x [,out])”计算非x元素的真值。

import numpy
numpy.logical_not(mylist)

[http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.logical_not.html](带有相同的示例)

例:

import numpy
mylist  = [True , True, False]
print (mylist)

返回[True,True,False]

mylist=numpy.logical_not(mylist)
print (mylist)

返回[False False True]

Marcel Flygare answered 2020-01-23T15:55:05Z
6 votes

为什么不只使用简单的列表理解呢?

mylist[:] = [not x for x in mylist]
mVChr answered 2020-01-23T15:55:25Z
3 votes

我会按照其他人说的做,但是为了记录替代方案,您也可以

import operator
myList = map(operator.not_, myList)
Tyler Crompton answered 2020-01-23T15:55:45Z
3 votes

numpy.invert是另一个不错的选择:

x = [False, True, True] 
not_x = np.invert(x) # [True, False, False]
gebbissimo answered 2020-01-23T15:56:05Z
2 votes

那下面呢

>>> import numpy
>>> list(numpy.asarray(mylist)==False)
Gerben answered 2020-01-23T15:56:25Z
translate from https://stackoverflow.com:/questions/10678441/flipping-the-boolean-values-in-a-list-python