本文介绍了设置迭代顺序因运行而异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Python集的迭代顺序(具有相同的内容)因运行而异,以及从运行到运行使其一致的选项是什么?

Why does the iteration order of a Python set (with the same contents) vary from run to run, and what are my options for making it consistent from run to run?

我知道Python集的迭代顺序是任意的。如果我将'a','b'和'c'放入一个集合然后迭代它们,它们可能会以任何顺序返回。

I understand that the iteration order for a Python set is arbitrary. If I put 'a', 'b', and 'c' into a set and then iterate them, they may come back out in any order.

我是什么观察到的是,在程序运行中,顺序保持不变。也就是说,如果我的程序连续两次迭代同一个集合,那么我两次都得到相同的顺序。但是,如果我连续两次运行程序,则顺序会从运行更改为运行。

What I've observed is that the order remains the same within a run of the program. That is, if my program iterates the same set twice in a row, I get the same order both times. However, if I run the program twice in a row, the order changes from run to run.

不幸的是,这打破了我的一个自动化测试,它只是比较输出来自我的计划的两次运行。我不关心实际的订单,但我希望它在运行之间保持一致。

Unfortunately, this breaks one of my automated tests, which simply compares the output from two runs of my program. I don't care about the actual order, but I would like it to be consistent from run to run.

我提出的最佳解决方案是:

The best solution I've come up with is:


  1. 将集合复制到列表中。

  2. 对列表应用任意排序。

  3. 迭代列表而不是集合。

是否有更简单的解决方案?

Is there a simpler solution?

注意:我在StackOverlow上发现了类似的问题,但没有一个能解决从运行到运行获得相同结果的特定问题。

Note: I've found similar questions on StackOverlow, but none that address this specific issue of getting the same results from run to run.

推荐答案

你想要的是不可能的。任意意味着任意。

What you want isn't possible. Arbitrary means arbitrary.

我的解决方案与您的解决方案相同,如果您希望能够将其与另一个进行比较,则必须对该集进行排序。

My solution would be the same as yours, you have to sort the set if you want to be able to compare it to another one.

这篇关于设置迭代顺序因运行而异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 01:21