JSW*_*189 3 python algorithm list
确定列表中两个元素是否相同的最有效方法是什么?例如:
>>> has1dup(["one", "one", "two"])
True
>>> has1dup(["one", "two", "three"])
False
>>> has1dup(["one", "one", "one"])
False
Run Code Online (Sandbox Code Playgroud)
我已成功使用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
Run Code Online (Sandbox Code Playgroud)
Joc*_*zel 11
您可以看到有多少个唯一值set.如果集合中的项目少于列表中的项目,则一个项目是重复的:
def has1dup(lst):
return len(lst)-1 == len(set(lst))
Run Code Online (Sandbox Code Playgroud)