【发布时间】:2019-09-20 23:52:10
【问题描述】:
我想用 Python 写一个脚本,我手里有一个 ABDEB 的词。我想把这个词变成一个数组,然后把这个词里面的字母打乱,得到不同组合的词。此外,这些组合可能包含重复的字母并构成一列;
BBBED, 欧亚大陆, ADDEA,
等等
毕竟,我想把这些词放到一个文本文件中。
我该怎么做?
如果您能提供帮助,我将不胜感激。
【问题讨论】:
标签: python python-3.x random shuffle
我想用 Python 写一个脚本,我手里有一个 ABDEB 的词。我想把这个词变成一个数组,然后把这个词里面的字母打乱,得到不同组合的词。此外,这些组合可能包含重复的字母并构成一列;
BBBED, 欧亚大陆, ADDEA,
等等
毕竟,我想把这些词放到一个文本文件中。
我该怎么做?
如果您能提供帮助,我将不胜感激。
【问题讨论】:
标签: python python-3.x random shuffle
random.shuffle 是你的朋友,根据文档
random.shuffle(x[, random]) .
将序列 x 打乱。
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,它会一次性为您提供all 可能的组合,然后使用random.choce 从那里选择一个元素
来自文档:
itertools.combinations_with_replacement(iterable, r)
从输入可迭代中返回 r 个长度的元素子序列,允许单个元素重复多次。random.choice(seq)
从非空序列 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
【讨论】:
试试这个。
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")
【讨论】:
最简单的方法之一是使用 random.shuffle 函数: https://docs.python.org/3/library/random.html#random.shuffle
至于将单词写入文件,这是一个相当简单的练习,所以我建议稍微搜索一下这个答案,因为有很多方法可以做到这一点,而且你的规范有点不清楚。
【讨论】:
使用 random.shuffle。它比简单的算法更快,因为它使用了 Fisher-Yates shuffle。它在 O(n) 时间内运行,是一个完美的随机播放。
您自己的实现可能会在 O(n^2) 时间内运行
【讨论】: