Python:检查列表项是否有补码

时间:2015-03-24 02:24:43

标签: python python-2.7

我有一个清单:

 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中这样做?谢谢

1 个答案:

答案 0 :(得分:1)

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