Python 中集合的迭代顺序
如果我有两个相同的集合,意味着 a == b
给我 True
,它们会有相同的迭代顺序吗?我尝试过,它有效:
>>> foo = set("abc")
>>> bar = set("abc")
>>> zip(foo, bar)
[('a', 'a'), ('c', 'c'), ('b', 'b')]
我的问题是,我是幸运的,还是这种行为有保证?
If I have two identical sets, meaning a == b
gives me True
, will they have the same iteration order? I tried it, and it works:
>>> foo = set("abc")
>>> bar = set("abc")
>>> zip(foo, bar)
[('a', 'a'), ('c', 'c'), ('b', 'b')]
My question is, was I lucky, or is this behavior guaranteed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它们的结果相同并不是巧合:实现恰好是确定性的,因此两次创建相同的集合会产生相同的顺序。但 Python 并不保证这一点。
如果您以两种不同的方式创建相同的集合:
...您可以获得不同的排序:
It wasn't just a coincidence that they came out the same: the implementation happens to be deterministic, so creating the same set twice produces the same ordering. But Python does not guarantee that.
If you create the same set in two different ways:
...you can get different ordering:
你很幸运,订单无法保证。唯一可以保证的是这些集合将具有相同的元素。
如果您需要某种可预测性,可以像这样对它们进行排序:
zip(sorted(foo),sorted(bar))
。You were lucky, the order is not guaranteed. The only thing that's guaranteed is that the sets will have the same elements.
If you need some sort of predictability, you could sort them like this:
zip(sorted(foo), sorted(bar))
.否:
PS 我不知道
__hash__
覆盖是否必要。我只是尝试了一些我认为会打破这个的东西,而且它确实做到了。No.:
P.S. I have no idea if the
__hash__
override is necessary. I just tried something I thought would break this, and it did.是的,你很幸运。参见示例:
这给了我结果:
Yes, you were lucky. See for example:
Which gave me the result:
我想说你很幸运。不过,也可能是因为集合中的元素相同,所以它们以相同的顺序存储。您不希望依赖这种行为。
I'd say you got lucky. Though, it might also be that, since the elements in the set were the same, they were stored in the same order. This behavior is not something you'd want to rely on.