在python中检查重复项的最快方法是什么?

The*_*One 3 python dictionary hashmap set duplicates

使用字典似乎是理想的.

例如:

history = {}
for i in collection:
    if i not in history:
        history[i] = None
        # fancy computation here
Run Code Online (Sandbox Code Playgroud)

使用set()类型会一样快; set()不要求我向哈希键添加傻无值.

Mar*_*ers 6

是的,你应该使用一套.


使用set()类型会一样快;

不,它不会那么快.它会更快.


更新

有些人发布的基准测试显示set比dict慢.我认为这有点令人惊讶,因为它们基本上具有相同的底层实现,除了set更简单.我认为我找到了缓慢的原因:

def set_way():
    my_set = set()
    my_set_add = my_set.add   # remember the method
    for ele in x:
        if ele not in my_set:
            my_set_add(ele)   # call the method directly
Run Code Online (Sandbox Code Playgroud)

结果:

dict time : 1.896939858077399
set time : 1.8587076107880456
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,Set现在稍快一些.