1. 程式人生 > >檢視一個列表中是否出現重複元素

檢視一個列表中是否出現重複元素

轉載地址:

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