python - 具有更多随机化的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..)
,因为这会产生一个非常不必要的长列表。
解决方案
一种方法是在生成排列之前和/或之后洗牌。
以供参考:
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)]
推荐阅读
- c# - RemObjects RemotingSDK 的替代方案
- c# - 如何将参数添加到 .Net Core 结构化日志记录而不在消息中引用它?
- google-cloud-platform - 我有 Kubernetes 集群。从外部源(集群外部)下载文件需要多少费用?
- java - 在 Activity1 框架上使用从 Activity2 的接口检索到的数据时遇到问题
- python - 如何解决pytorch中Multi Head Attention的大小不匹配?
- c - 如何在 Lunux 中使用 C 编写重定向代码?
- angular - Angular 中的 StaticInjectorError 路由器
- python - 我有两个大小相同的列表,我想将这两个列表转换为具有唯一键的字典
- swift - 核心数据删除后TableView刷新问题
- css - 无法解析 CSS