Python 中元组和冻结集的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14422409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between tuples and frozensets in Python
提问by legends2k
I'm learning Python 3 using The Quick Python Book, where the author talks about frozensets, stating that since sets are mutable and hence unhashable, thereby becoming unfit for being dictionary keys, their frozen counterparts were introduced. Other than the obvious difference that a tuple is an ordered data structure while frozenset, or more generally a set, is unordered, are there any other differences between a tuple and a frozenset?
我正在使用 The Quick Python Book 学习 Python 3,其中作者谈到了frozensets,指出由于集合是可变的,因此不可散列,因此不适合作为字典键,因此引入了它们的冻结对应物。除了元组是有序数据结构而frozenset或更一般的集合是无序的明显区别之外,元组和frozenset之间还有其他区别吗?
采纳答案by Volatility
tuplesare immutable lists, frozensetsare immutable sets.
tuples是不可变的lists,frozensets是不可变的sets。
tuplesare indeed an ordered collection of objects, but they can contain duplicates and unhashable objects, and have slice functionality
tuples确实是对象的有序集合,但它们可以包含重复和不可散列的对象,并具有切片功能
frozensetsaren't indexed, but you have the functionality of sets- O(1) element lookups, and functionality such as unions and intersections. They also can't contain duplicates, like their mutable counterparts.
frozensets未编入索引,但您具有sets- O(1) 元素查找的功能,以及并集和交集等功能。它们也不能包含重复项,就像它们的可变副本一样。
回答by Makoto
One difference that comes to mind is the issue of duplicates. A tuple of (1, 1, 1, 1, 2, 2, 2)would be exactly what you expect, but a frozenset would remove all of those duplicates, leaving you with frozenset([1, 2]).
想到的一个区别是重复问题。一个 的元组(1, 1, 1, 1, 2, 2, 2)正是您所期望的,但是frozenset 会删除所有这些重复项,为您留下frozenset([1, 2]).
回答by Joop
Volatility does mention that frozensets are not indexed. I was looking at the other functionality, so did not immediately realize that standard python slicing is not possible.
Volatility 确实提到了frozensets 没有被索引。我正在查看其他功能,所以没有立即意识到标准 python 切片是不可能的。
a = frozenset((1, 1, 1, 1, 2, 2, 2)) # results in frozenset([1, 2])
print a[0]
will give error:
会报错:
TypeError: 'frozenset' object does not support indexing
Obvious from fact that it is not indexed, but though it was worth adding explicitly here
很明显,它没有被索引,但尽管值得在这里明确添加
回答by F1Rumors
Somewhat counter intuitive - what about this bon mot:
有点违反直觉 - 这个 bon mot 怎么样:
sss = frozenset('abc')
sss |= set('efg')
Will yield:
将产生:
frozenset(['a', 'c', 'b', 'e', 'g', 'f'])
Of course, this is equivalent to x = x | y, so not changing the original frozenset, but it doesn't half make a mockery of the term 'immutable' to the code reviewer!
当然,这等价于 x = x | 是的,所以不改变原始的frozenset,但它并没有对代码者对术语“不可变”进行嘲讽!

