我有一张单子,里面有一对。例如

pair = ['x', 'xc']

我需要找到问题所在,反之亦然。我有以下代码来实现它。我正在使用Python2.2(不要问)。任何更清洁的解决方案都是有益的。
def getComplement(pair, core):
    complement = None
    for element in pair:
       if element != core:
         complement = element

    return complement

print getComplement(['x', 'xc'], 'xc') # 'x'
print getComplement(['x', 'xc'], 'x')  # 'xc'

最佳答案


return pair[0] if pair[0] != core else pair[1]


return set(pair) - [core]


return  pair[not pair.index(core)]

所以还有很多其他的方法

关于python - 在长度为2的列表中查找另一个元素的pythonic解决方案,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20892950/

10-11 22:07
查看更多