在Python中随机化string列表的最佳方法

我接收到一个string列表作为input,并且需要返回一个带有相同string的列表,但是按照随机顺序。 我必须允许重复 – 相同的string可能在input中出现一次或多次,并且在输出中必须出现相同的次数。

我看到了几种“蛮力”的方法(使用循环,上帝禁止),其中我正在使用的其中之一。 然而,认识Python可能是一个很酷的单线程完成工作,对吧?

>>> import random >>> x = [1, 2, 3, 4, 3, 4] >>> random.shuffle(x) >>> x [4, 4, 3, 1, 2, 3] >>> random.shuffle(x) >>> x [3, 4, 2, 1, 3, 4] 

看起来这是最简单的方法,如果不是最真正的随机( 这个问题更充分的解释了这个限制): http : //docs.python.org/library/random.html#random.shuffle

给定一个string项目 ,这是一个单行的:

 ''.join([str(w) for w in random.sample(item, len(item))]) 

您必须将string读入数组,然后使用洗牌algorithm。 我推荐Fisher-Yates shuffle