2017-01-16 32 views
0

我有三个列表Main,SupplementalAuxiliary,都包含几个字符串。将列表项目随机放入字符串的部分

我想从这些随机元素的组合中产生一个新的字符串。 Main将有一个定义的指数,但其他指标应该随机选择。这些出来的顺序也应该是随机的。

这是什么将完成这项工作:

main = main[5] 
supp = random.choice(supplemental) 
aux = random.choice(auxiliary) 

all = [main, supp, aux] 

print(random.choice(all) + random.choice(all) + random.choice(all)) 

然而,这是不是特别优雅,造成碰撞的机会很高。

有没有更好的方法来思考这个问题,并且不会导致列表被挑选的问题?

回答

1

好像要random.shuffle您的项目:

>>> import random 
>>> all_ = ['a', 'b', 'c'] # I use explicit strings instead of your [main, supp, aux] 
>>> random.shuffle(all_) 
>>> print(''.join(all_)) 
cba 
>>> print(''.join(all_)) 
bac 

随着shuffle也不会有除非如果你的列表中包含重复的项目冲突。

random.sample也可以使用,如果你不想额外的洗牌步骤。它并不会改变原来的列表,并在输入含有超过3项工作,你只需要3:

>>> print(''.join(random.sample(all_, 3))) 
bca 
+0

'random.sample(ALL_,3)'将节省您的洗牌。另外,我怀疑第二个'print'产生了不同的输出而没有先洗牌;) – schwobaseggl

+0

好点。我已经更新了答案 – MSeifert

相关问题