【问题标题】:How to check if a list contains duplicate items?如何检查列表是否包含重复项?
【发布时间】:2018-06-20 22:29:00
【问题描述】:

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

这是我的想法:

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

if #lst contains no duplicates :
    print("success")
else:
    print("duplicate found")

提前致谢。

【问题讨论】:

标签: python validation


【解决方案1】:

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

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

if len(set(lst)) == len(lst):
    print("success")
else:
    print("duplicate found")

【讨论】:

  • lst 是字典列表时,这不起作用。 set(lst) 然后抛出 TypeError: unhashable type: 'dict'
【解决方案2】:

利用 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

【讨论】:

  • 您可以简化为return len(listObj) != len(set(listObj))
【解决方案3】:

检查这个,最简单的方法(至少对我来说)..

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")

【讨论】:

    【解决方案4】:
    def check_duplicates(lst):
        seen = {}
        for item in lst:
            if seen.get(item):
                print("duplicate found")
                return
            else:
                seen[item] = True
        print("success")
    

    【讨论】:

      【解决方案5】:
      def checkDuplicate():
          count = {}
          for item in lst:
                  if item not in count:
                      count[item] = 1
                  else:
                      return True
          return False
      
      

      【讨论】:

      • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多