我有一个包含一对的列表。例如
pair = ['x', 'xc']
问题给出了x
,我需要找到xc
,反之亦然。我有以下代码来实现它。我正在使用Python 2.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)]
还有很多其他方法
关于用于在长度为 2 的列表中查找另一个元素的 pythonic 解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892950/