3

在 Python 中,给定一组可比较的、可散列的元素s,是散列frozenset(s)还是tuple(sorted(s)).

4

1 回答 1

3

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

frozenset创建 a比创建 a 更快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,这在此处进行了说明。

frozenset和之间的查找时间差别很小tuple这里

于 2013-01-26T07:06:41.250 回答