如何检查列表是否包含重复项?

cbu*_*800 2 python validation

我想验证列表以确保没有重复的项目.我的问题是我不知道如何在if语句中执行此操作.如果列表中有重复项,python中是否存在返回False的方法或内容?

这就是我的想法:

lst = ["1","2","3","3","4"]

if #lst contains no duplicates :
    print("success")
else:
    print("duplicate found")
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Thi*_*hib 10

如Jkdc所述,将其转换为集合并比较长度

lst = ["1","2","3","3","4"]

if len(set(lst)) == len(lst):
    print("success")
else:
    print("duplicate found")
Run Code Online (Sandbox Code Playgroud)

  • 当`lst`是词典列表时,这不起作用。然后,set(lst)抛出TypeError:不可散列的类型:dict。 (2认同)

Poi*_*oiz 8

利用 Python 可能不包含重复项的事实set。该has_duplicate()函数负责确定列表是否包含重复项。

def has_duplicates(listObj):
    return len(listObj) != len(set(listObj))


print(has_duplicates([1, 2, 1, 1, 4, 7]))    ## PRINTS: True
print(has_duplicates([9, 2, 5, 4, 7]))       ## PRINTS: False
Run Code Online (Sandbox Code Playgroud)