首页 > 解决方案 > 具有更多随机化的python排列

问题描述

我正在尝试从索引列表中生成排列,目前我正在使用itertools.permutation. 没关系,除了我需要索引的真正随机性质,因为我将无法选择所有排列,而是选择整个集合(初始排列)的一个非常短的子集进行模拟。

For itertools.permutation排列元组根据输入迭代的顺序以字典顺序发出。因此,如果输入的可迭代对象已排序,则组合元组将按排序顺序生成。

import itertools
for ind, idxs in enumerate(itertools.permutations(range(5))):
  print(ind)
  print(idxs)
  print('--------')
0
(0, 1, 2, 3, 4)
--------
1
(0, 1, 2, 4, 3)
--------
2
(0, 1, 3, 2, 4)
--------
3
(0, 1, 3, 4, 2)
--------
4
(0, 1, 4, 2, 3)
--------
5
(0, 1, 4, 3, 2)
--------
6
(0, 2, 1, 3, 4)
--------
7
(0, 2, 1, 4, 3)
--------
8
(0, 2, 3, 1, 4)
--------
9
(0, 2, 3, 4, 1)
--------
10
(0, 2, 4, 1, 3)
--------
11
(0, 2, 4, 3, 1)
--------
12
(0, 3, 1, 2, 4)
--------
13
(0, 3, 1, 4, 2)
--------

我肯定想到的一种解决方案是每次都对列表​​进行洗牌以获得随机顺序,但这使得排列的想法过时了,这是不希望的,因为有可能多次生成相同的样本。排列应该迭代生成,所以我不能这样做list(itertools.permutation..),因为这会产生一个非常不必要的长列表。

标签: pythonpython-3.xalgorithmrandompermutation

解决方案


一种方法是在生成排列之前和/或之后洗牌。

以供参考:

import itertools
import random
a = list(range(3))
print("original =",a)
random.shuffle(a)
print("shuffled =",a)
permutations = list(itertools.permutations(a))
print("permutations of shuffled array =",permutations)
random.shuffle(permutations)
print("shuffled permutations of shuffled array =",permutations)
original = [0, 1, 2]
shuffled = [1, 0, 2]
permutations of shuffled array = [(1, 0, 2), (1, 2, 0), (0, 1, 2), (0, 2, 1), (2, 1, 0), (2, 0, 1)]
shuffled permutations of shuffled array = [(0, 1, 2), (2, 0, 1), (2, 1, 0), (1, 0, 2), (1, 2, 0), (0, 2, 1)]

推荐阅读