这似乎有效,应该能够处理任何可迭代的,而不仅仅是list
s。它尽可能短路以最大限度地提高效率。适用于 Python 2 和 3。
def only1(iterable):
for i, x in enumerate(iterable): # check each item in iterable
if x: break # truthy value found
else:
return False # no truthy value found
for x in iterable[i+1:]: # one was found, see if there are any more
if x: return False # found another...
return True # only a single truthy value found
testcases = [ # [[iterable, expected result], ... ]
[[ ], False],
[[False, False, False, False], False],
[[True, False, False, False], True],
[[False, True, False, False], True],
[[False, False, False, True], True],
[[True, False, True, False], False],
[[True, True, True, True], False],
]
for i, testcase in enumerate(testcases):
correct = only1(testcase[0]) == testcase[1]
print('only1(testcase[{}]): {}{}'.format(i, only1(testcase[0]),
'' if correct else
', error given '+str(testcase[0])))
输出:
only1(testcase[0]): False
only1(testcase[1]): False
only1(testcase[2]): True
only1(testcase[3]): True
only1(testcase[4]): True
only1(testcase[5]): False
only1(testcase[6]): False