Hashing frozenset与排序的元组

时间:2013-01-26 06:26:56

标签: python hash python-3.x

在Python中,给定一组可比较的可散列元素s,最好是哈希frozenset(s)tuple(sorted(s))

1 个答案:

答案 0 :(得分:2)

这取决于你在做什么。创建frozenset()比对tuple进行排序要快,但frozenset占用的内存比tuple更多。

创建frozenset而不是tuple

的速度更快
import timeit

import random as rn

x = range(2000)
rn.shuffle(x)
x = tuple(x)

def get_frozen_set(x):
    return frozenset(x)

def get_sorted_tuple(x):
    return sorted(x)

n = 10000

t1 = timeit.timeit('get_frozen_set(x)', 'from __main__ import x, get_frozen_set', number = n)
print 'create a frozenset:', t1
t2 = timeit.timeit('get_sorted_tuple(x)','from __main__ import x, get_sorted_tuple', number = n)
print 'sort tuple:', t2

结果:

create a frozenset: 0.85803164112
sort tuple: 6.65848886198

虽然开始tuple的差异非常大,但很短。对于n = 20

结果:

create a frozenset: 0.0124568308591
sort tuple: 0.0257906431368

frozenset占用了更多memory,这说明here

frozensettuple之间的查找时间差别很小,here