后浪云Python教程:python数组判断是否存在重复元素

后浪云Python教程:python数组判断是否存在重复元素插图

方法一:通过排序,然后判断相邻的两个元素是否相等

代码:

def judgeDuplicated(array):
    array.sort()
    count=0
    while count<len(array)-1:
        if array[count]==array[count+1]:
            return True
        else:
            count+=1
    return False
if __name__ == '__main__':
    array=[1,4,4,1]
    print(judgeDuplicated(array))

方法二:使用字典

代码:

def judgeRepeated(array):
    nums={}
    for i in array:
        if i  not in nums:
            nums[i]=True
        else:
            return True
    return False

方法三:使用集合set(set和其他方法一样,存储的数据都是无序不重复的数据),我们可以通过判断列表转元组之后的长度是否和原长度相等来实现

代码:

def judgeRepeatedThird(array):
    if len(set(array))==len(array):
        return False
    else:
        return True
THE END