我有一个列表:
listA = ['P', 'Q', ['not', 'R'], ['not', 'S']]
Input1 : ['not','P'] - Return True as complement exists
Input2 : 'S' - Return True as complement exists
我想确定上面的列表 (listA) 中是否存在 ['not','P'](P 的赞美)。它在这种情况下存在,因此应该返回 True。
我如何在 python 中执行此操作?谢谢
请您参考如下方法:
def comp(el):
if type(el) == str:
return ['not', el]
else:
return el[1]
listA = ['P', 'Q', ['not', 'R'], ['not', 'S']]
comp(['not', 'P']) in listA # True
comp('S') in listA # True
不过,更好的方法可能是将您的逻辑值包装在一个类中:
class Logic_Value(object):
def __init__(self, name, negation=False):
self.name = name
self.negation = negation
def __neg__(self):
return Logic_Value(self.name, not self.negation)
def __str__(self):
return '~' + self.name if self.negation else self.name
然后检查否定是否在列表中变为:
P = Logic_Value('P')
-P in listA # True if not P is in listA
