如何在 Python 中进行随机洗牌?

How to do random shuffling in Python?

我想在 Python 中写一个脚本,我手上有一个关于 ABDEB 的词。我想把这个单词做成一个数组,然后把单词里面的字母打乱,得到不同组合的单词。此外,这些组合可能包含重复的字母并构成一列;

BBBED, 欧洲经济区, 阿德达,

等等

毕竟,我想把这些话放到一个文本文件中。

我该怎么做?

如果您能提供帮助,我将不胜感激。

最简单的方法之一是使用 random.shuffle 函数: https://docs.python.org/3/library/random.html#random.shuffle

至于将单词写入文件,这是一个相当简单的练习,所以我建议稍微搜索一下该答案,因为有很多方法可以做到这一点,而且您的规范有点不清楚。

random.shuffle 是你的朋友,根据文档

random.shuffle(x[, random]) .
Shuffle the sequence x in place.

import random

#Convert string to list of chars
li = list('ABDEB')

for i in range(5):
    #Shuffle the list, the last shuffled list is shuffled every time
    random.shuffle(li)
    #Convert list to string again and print
    print(''.join(li))

输出可能看起来像

DBEBA
ABEBD
BABDE
BADEB
BDAEB

或者您可以每次都从相同的基本字符串开始

import random

for i in range(5):
    li = list('ABDEB')
    random.shuffle(li)
    print(''.join(li))

对于带替换的随机播放,您实际上可以使用 itertools.combibations_with_replacement and it will give you all possible combinations in one go, then use random.choce 从那里选择一个元素

来自文档:

itertools.combinations_with_replacement(iterable, r)
Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

random.choice(seq)
Return a random element from the non-empty sequence seq.

from itertools import combinations_with_replacement
import random

li = list('ABDEB')

#Get all possible combinations with repetitions
res = [''.join(item) for item in combinations_with_replacement(li,len(li))]

#Use random.choice to pick a element from res
for i in range(5):
    print(random.choice(res))

输出看起来像

DDEEE
ABBBE
ADDDD
BBDDB
AADDB

使用random.shuffle。它比原始算法更快,因为它使用 Fisher-Yates 洗牌。它在 O(n) 时间内 运行s 并且是一个完美的洗牌。

您自己的实现可能会在 O(n^2) 时间内 运行

试试这个。

import itertools
x = list('ABDEB')
a=[''.join(p) for p in itertools.product(x, repeat=len(x))]
print(a)

输出:

['AAAAA', 'AAAAB', 'AAAAD', 'AAAAE', 'AAAAB', 'AAABA',...]

要保存到文件,请使用以下命令。

import numpy as np
np.savetxt('test.txt', a, delimiter=" ", fmt="%s")