Jef*_*eff 15 python random shuffle
是否有一种直接的方法在Python中返回一个混洗数组而不是将它混洗到位?
例如,而不是
x = [array]
random.shuffle(x)
Run Code Online (Sandbox Code Playgroud)
我正在寻找类似的东西
y = shuffle(x)
Run Code Online (Sandbox Code Playgroud)
维持x.
注意,我不是在寻找一个函数,而不是像:
x=[array]
y=x
random.shuffle(x)
Run Code Online (Sandbox Code Playgroud)
Aus*_*all 19
sorted使用key返回随机值的函数:
import random
sorted(l, key=lambda *args: random.random())
Run Code Online (Sandbox Code Playgroud)
要么
import os
sorted(l, key=os.urandom)
Run Code Online (Sandbox Code Playgroud)
Aar*_*our 12
实现自己的使用非常简单random.我会写如下:
def shuffle(l):
l2 = l[:] #copy l into l2
random.shuffle(l2) #shuffle l2
return l2 #return shuffled l2
Run Code Online (Sandbox Code Playgroud)
写自己的.
import random
def shuffle(x):
x = list(x)
random.shuffle(x)
return x
x = range(10)
y = shuffle(x)
print x # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print y # [2, 5, 0, 4, 9, 3, 6, 1, 7, 8]
Run Code Online (Sandbox Code Playgroud)