如何在Python中生成数组的排列?
我有一个包含 27 个元素的数组,我不想生成数组的所有排列 (27!) 我需要 5000 个随机选择的排列,任何提示都会有用......
I have an array of 27 elements, and I don't want to generate all permutations of array (27!)
I need 5000 randomly choosed permutations, any tip will be useful...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要生成一种排列,请使用
random.shuffle
并存储结果的副本。循环重复此操作,每次检查是否有重复项(但可能不会有重复项)。一旦结果集中有 5000 个项目,就停止。为了解决评论中的观点,Python 的 random 模块 基于 Mersenne Twister 的周期为
2**19937-1
,该周期要大得多比27!
所以它应该适合您的使用。To generate one permutation use
random.shuffle
and store a copy of the result. Repeat this operation in a loop and each time check for duplicates (there probably won't be any though). Once you have 5000 items in your result set, stop.To address the point in the comment, Python's random module is based on the Mersenne Twister and has a period of
2**19937-1
, which is considerably larger than27!
so it should be suitable for your use.10888869450418352160768000000
我喜欢大数字! :)并且
10888869450418352160768000001
是 PRIME!!编辑:
警告:如果 RNG 很糟糕,这将永远不会停止!
10888869450418352160768000000
I love big numbers! :)AND
10888869450418352160768000001
is PRIME!!EDIT:
WARNING: This wont ever stop if RNG is bad!
itertools.permutations
。它是一个生成器,因此它不会创建整个排列列表。你可以随机跳过,直到达到 5000 为止。itertools.permutations
. It's a generator, so it won't create the whole list of permutations. You could skip randomly until you've got 5000.用法:
perm_given_index(['a','b','c'], 3)
这使用 Lehmer 代码进行排列,因为
j
的值与其匹配。Usage:
perm_given_index(['a','b','c'], 3)
This uses the Lehmer code for the permutation as the values of
j
match that.您可以尝试实现
random_permutation
itertools Recipe< /a>.为了方便起见,我使用第三方库more_itertools
,为我们实现了这个秘诀:为函数的每次调用创建一个随机排列。我们可以制作一个生成器,为
n
调用生成这些结果。我们将实现这个生成器并通过一个简短的示例演示随机结果:对于您的具体问题,将可迭代次数和调用次数
n
替换为适当的值,例如random_permute_generator(iterable, n=5000 )
。另请参阅
more_itertools
文档 有关此工具的更多信息。详细信息
对于那些有兴趣的人,这里是实际的食谱。
来自 itertools 食谱:
You can try implementing the
random_permutation
itertools recipes. For convenience I use a third-party library,more_itertools
, that implements this recipe for us:A random permutation is created for every call of the function. We can make a generator that yields these results for
n
calls. We will implement this generator and demonstrate random results with an abridged example:For your specific problem, substitute the iterable and number of calls
n
with the appropriate values, e.g.random_permute_generator(iterable, n=5000)
.See also
more_itertools
docs for further information on this tool.Details
For those interested, here is the actual recipe.
From the itertools recipes:
您可能需要 itertools.permutations() 函数。一定喜欢 itertools 模块!
注意:2.6 中的新增功能
You may want the itertools.permutations() function. Gotta love that itertools module!
NOTE: New in 2.6