python - 散列 frozenset 与 tuple of sorted

标签 python hash python-3.x

在 Python 中,给定一组可比较的、可散列的元素 s,散列 frozenset(s)tuple(sorted(s)) 哪个更好?

最佳答案

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

创建 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 之间的查找时间差异非常小

关于python - 散列 frozenset 与 tuple of sorted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14534495/

相关文章:

python - 正则表达式多行语法帮助 (python)

python - 如何通过在单个单元格中删除 NaN 来调整数据框的大小?

python - cx_Oracle连接速度慢

python - 从DockerFile修改Python脚本

python - 我可以在 Python 中使用前置元素而不是 append 来扩展列表吗?

python - 在 Pyramid 框架内运行脚本(即没有服务器)

javascript - Angular - 将指令附加到 future 元素

perl - 将 MD5/SHA1 哈希从二进制转换为十六进制摘要

Ruby:同时循环两个散列,其中一个是嵌套散列

perl - 将散列传递给子例程