具有更多随机化的python置换

2024-06-25 23:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从索引列表中生成置换,目前,我使用itertools.permutation。没关系,只是我需要一个真正随机的索引,因为我不能选择所有的排列,而是选择整个集合(初始的)的一个很短的子集进行模拟

对于itertools.permutation置换元组根据输入可数的顺序按字典顺序发出。因此,如果对输入iterable进行排序,则组合元组将按排序顺序生成

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..),因为这将产生一个真正不必要的长列表


Tags: import列表for字典排序顺序iterable子集
3条回答

使用random.sample

permutations = list(itertools.permutations(range(5)))
permutation = random.sample(permutations, k=4)
# run 1
>>> random.sample(permutations, k=4)
[(0, 4, 1, 2, 3), (4, 0, 1, 3, 2), (3, 2, 0, 4, 1), (1, 2, 3, 4, 0)]

# run 2
>>> random.sample(permutations, k=4)
[(2, 1, 4, 0, 3), (0, 3, 4, 1, 2), (3, 1, 4, 0, 2), (0, 3, 4, 2, 1)]

# run 3
>>> random.sample(permutations, k=4)
[(3, 4, 1, 0, 2), (3, 0, 1, 2, 4), (0, 4, 1, 2, 3), (3, 4, 2, 0, 1)]

# and so on

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

供参考:

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)]

生成随机排列:如果您只使用其中的一小部分k,那么您获得两倍相同的概率是k/n

相关问题 更多 >