查看一个列表中是否出现重复元素

转载地址:

http://greenteapress.com/thinkpython2/code/has_duplicates.py

《像计算机科学家一样思考Python》 11.10练习中的练习 11-4

# 通过使用set函数来确定这个需求,就这段代码 return len(set(t)) < len(t) 

# 相当简单,努力Get一下。

def has_duplicates(t):
    """Checks whether any element appears more than once in a sequence.

    Simple version using a for loop.

    t: sequence
    """
    d = {}
    for x in t:
        if x in d:
            return True
        d[x] = True
    return False


def has_duplicates2(t):
    """Checks whether any element appears more than once in a sequence.

    Faster version using a set.

    t: sequence
    """
    return len(set(t)) < len(t)


if __name__ == '__main__':
    t = [1, 2, 3]
    print(has_duplicates(t))
    t.append(1)
    print(has_duplicates(t))

    t = [1, 2, 3]
    print(has_duplicates2(t))
    t.append(1)
    print(has_duplicates2(t))

猜你喜欢

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