可以使用列表解析+count简单实现:
def get_ele(alist): return [i for i in alist if alist.count(i) == 2][0] print get_ele([1,2,3,-1,-1])
一个列表中只有一个数字出现了一次,其他都出现了两次,可以这么写, 利用异或运算的性质:
get_once_ele = lambda alist: reduce(lambda a,b: a ^ b, alist) print get_once_ele([2, 2, 1, 1, 4]) print get_once_ele([1, 1, 0, 2, 3, 2, 3]) print get_once_ele([-1, 0, 0, 2, 2])