可能重复:
使用python随机播放数组
假设我有一个列表myList=[1,2,3,4,5],我想随机乱码:
disorder(myList) # myList is something like [5,3,2,1,4] or [3,5,1,2,4] now
Run Code Online (Sandbox Code Playgroud)
我使用的方式是
from random import randint
upperBound = len(myList)-1
for i in range(10):
myList.insert(randint(0, upperBound), myList.pop(randint(0, upperBound)))
Run Code Online (Sandbox Code Playgroud)
这有效,但我认为这显然不够优雅.我想知道是否有一种优雅而有效的方式来实现我的目标.
如果您已经随机导入:
random.shuffle(myList)
Run Code Online (Sandbox Code Playgroud)
它在myList适当的地方洗牌.这意味着您只需要运行此命令,不要使用此函数的返回值,这始终是None.
用于random.shuffle()将列表原位洗牌:
>>> import random
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(l)
>>> l
[0, 2, 8, 7, 9, 1, 3, 4, 6, 5]
Run Code Online (Sandbox Code Playgroud)