在 Python 中随机化字符串列表的最佳方法

我接收一个字符串列表作为输入,并且需要返回一个具有相同字符串但是随机顺序的列表。我必须允许重复-相同的字符串可能出现一次或多次在输入和必须出现相同的次数在输出。

我看到了几种“蛮力”方式(使用循环,但愿不是这样) ,其中一种我正在使用。但是,知道 Python 可能有一个很酷的一行程序可以完成这项工作,对吗?

111928 次浏览

Looks like this is the simplest way, if not the most truly random (this question more fully explains the limitations): http://docs.python.org/library/random.html#random.shuffle

>>> 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]

You'll have to read the strings into an array and then use a shuffling algorithm. I recommend Fisher-Yates shuffle

Given a string item, here is a one-liner:

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


b = []
a = int(input(print("How many items you want to shuffle? ")))
for i in range(0, a):
n = input('Please enter a item: ')
b.append(n)


random.shuffle(b)


print(b)

In python 3.8 you can use the walrus to help cram it into a couple of lines First you have to create a list from the string and store it into a variable. Then you can use random to shuffle it. Then just join the list back into a string.

random.shuffle(x := list("abcdefghijklmnopqrstuvwxyz"))
x = "".join(x)