检测列表中的所有元素是否唯一(非原创)

搬砖,引用来源于检测列表中的所有元素是否唯一
代码如下:

def all_unique(lst):
  return len(lst) == len(set(lst))

x = [1, 2, 3, 4, 5, 6]
y = [1, 2, 2, 3, 4, 5]

print(all_unique(x)) # True
print(all_unique(y)) # False

原理:我们知道集合set会将列表中一样的元素剔除重复的仅保留一个,因此如果列表中的元素均为独一无二的,set(lst) == lst, 如果列表中的元素存在重复的,则set(lst) != lst,从而len(lst) != len(set(lst)),那么return的语句为什么使用len(lst) == len(set(lst))而不使用set(lst) == lst呢?
请看如下代码:

x = [1, 2, 3, 4, 5, 6]

print(x == set(x))	# False
print(x)			# [1, 2, 3, 4, 5, 6]
print(set(x))		# {1, 2, 3, 4, 5, 6}
print(type(x))		# <class 'list'>
print(type(set(x)))	# <class 'set'>

虽然得到的listset中含有的元素一致,但是listset是不相等的,因此若return语句使用set(lst) == lst,返回值永远为False

猜你喜欢

转载自blog.csdn.net/u011699626/article/details/107924310