在Python中随机播放

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)

  • 这很短,但是缩放为O(n log n),而输入列表后跟`random.shuffle`的副本是O(n).参考:http://en.wikipedia.org/wiki/Shuffling#Shuffling_algorithms (13认同)

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)

  • +1:这是O(n),而`sorted(...,key = os.urandom)`在O(n log n)中. (2认同)

Fog*_*ird 8

写自己的.

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)

  • 我不想让你神奇地做任何事情,我只是问这样的功能是否存在于标准库中.我本身不需要副本,我想定义一个像x = shuffled([1 2 3 4 5])的数组,而不是必须在两行上定义它. (6认同)

min*_*hee 5

没有您正在寻找的功能.只需复制一份清单.