检查一个列表是否有重复元素

《像计算机科学家一样思考Python》第10章练习10-7

编写一个名为has_duplicates的函数接收一个列表,当其中任何一个元素出现多于一次时返回True。

它不应当修改原始列表。

※自己实现的代码(用while循环)

def has_duplicates(t):
    new_t = sorted(t)
    index = 0
    length = len(new_t)

    while index < length-1:
        if new_t[index] == new_t[index+1]:
            return True
        else:
            index += 1
    return False

t = ['a','b','C','D','A','C']
print(has_duplicates(t))

 ※官方实现的代码(用for循环)

def has_duplicates(s):
    t = list(s)
    t.sort()

    for i in range(len(t)-1):
        if t[i] == t[i+1]:
            return True
    return False

t = ['a','b','C','D','A','C']
print(has_duplicates(t))

猜你喜欢

转载自blog.csdn.net/sisqzy86/article/details/82907245