争夺Python列表

Cof*_*ain 4 python arrays shuffle list

在我提出问题之前,让我直截了当......

这不是重复是否有人知道一种方法来扰乱列表中的元素?使用python随机化一个数组,使用python随机化数组项顺序.我会解释为什么......

我想知道如何加扰数组,并制作一个新的副本.因为random.shuffle()修改了列表(并返回None),我想知道是否有其他方法可以做到这一点,所以我可以这样做scrambled=scramblearray().如果没有内置函数,我可以定义一个函数来尽可能地执行此操作.

eum*_*iro 17

def scrambled(orig):
    dest = orig[:]
    random.shuffle(dest)
    return dest
Run Code Online (Sandbox Code Playgroud)

和用法:

import random
a = range(10)
b = scrambled(a)
print a, b
Run Code Online (Sandbox Code Playgroud)

输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [6, 0, 2, 3, 1, 7, 8, 5, 4, 9]
Run Code Online (Sandbox Code Playgroud)


kof*_*ein 9

使用排序()。它返回一个新列表,如果您使用随机数作为密钥,它将被打乱。

import random
a = range(10)
b = sorted(a, key = lambda x: random.random() )
print a, b
Run Code Online (Sandbox Code Playgroud)

输出

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [5, 9, 0, 8, 7, 2, 6, 4, 1, 3]
Run Code Online (Sandbox Code Playgroud)