确定列表中的两个元素是否完全相同的最有效方法是什么?例如:
>>> has1dup(["one", "one", "two"])
True
>>> has1dup(["one", "two", "three"])
False
>>> has1dup(["one", "one", "one"])
False
我已经使用 if/else 语句成功地做到了这一点。但是,如果列表更大,则为一对写出每种可能性的任务将变得非常困难和耗时。有没有更快/更简单的方法来实现这一目标?
这是我尝试过的:
def has1dup(lst):
if lst[0] == lst[1] and lst[1] != lst[2]:
return True
elif lst[1] == lst[2] and lst[2] != lst[0]:
return True
elif lst[0] == lst[2] and lst[2] != lst[1]:
return True
else:
return False
最佳答案
您可以使用 set
看到有多少个唯一值。如果集合中的项比列表中的少一项,则其中一项是重复项:
def has1dup(lst):
return len(lst)-1 == len(set(lst))
关于python - 有效确定列表中三个项目中的两个是否相同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10343413/