我想验证列表以确保没有重复的项目。我的问题是我在if语句中不知道如何做到这一点。如果列表中有重复项,python中是否有一个方法或其他东西会返回False?
以下是我的想法:
lst = ["1","2","3","3","4"]
if #lst contains no duplicates :
print("success")
else:
print("duplicate found")
提前致谢。
答案 0 :(得分:8)
正如Jkdc所说,将其转换为集合并比较长度
lst = ["1","2","3","3","4"]
if len(set(lst)) == len(lst):
print("success")
else:
print("duplicate found")
答案 1 :(得分:2)
利用Python 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
函数负责确定列表是否包含重复项。
ts_fin <- ts(emea$Value, deltat = 1/24, start = c(2014, 21))
答案 2 :(得分:1)
检查这个,最简单的方法(至少对我而言)..
lst = ["1","2","3","3","4"]
status = True
for item in lst:
if lst.count(item) > 1:
# the count functions counts how many times the "item" is in lst
status = False
if status == True:
print("No duplicates")
else:
print("Duplicates found")
答案 3 :(得分:0)
def check_duplicates(lst):
seen = {}
for item in lst:
if seen.get(item):
print("duplicate found")
return
else:
seen[item] = True
print("success")
答案 4 :(得分:0)
def checkDuplicate():
count = {}
for item in lst:
if item not in count:
count[item] = 1
else:
return True
return False