我如何洗牌对象列表?我尝试了random.shuffle:

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

你可以构建一个函数,以一个列表作为参数,并返回一个打乱的列表版本:

from random import *

def listshuffler(inputlist):
    for i in range(len(inputlist)):
        swap = randint(0,len(inputlist)-1)
        temp = inputlist[swap]
        inputlist[swap] = inputlist[i]
        inputlist[i] = temp
    return inputlist

其他回答

你可以使用shuffle或者sample。它们都来自于随机模块。

import random
def shuffle(arr1):
    n=len(arr1)
    b=random.sample(arr1,n)
    return b

OR

import random
def shuffle(arr1):
    random.shuffle(arr1)
    return arr1

在某些情况下,当使用numpy数组时,使用random。Shuffle在数组中创建了重复数据。

另一种方法是使用numpy.random.shuffle。如果您已经在使用numpy,这是通用random.shuffle的首选方法。

numpy.random.shuffle

例子

>>> import numpy as np
>>> import random

使用random.shuffle:

>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


>>> random.shuffle(foo)
>>> foo

array([[1, 2, 3],
       [1, 2, 3],
       [4, 5, 6]])

使用numpy.random.shuffle:

>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


>>> np.random.shuffle(foo)
>>> foo

array([[1, 2, 3],
       [7, 8, 9],
       [4, 5, 6]])

'print func(foo)'将在使用'foo'调用时打印'func'的返回值。 然而,'shuffle'的返回类型是None,因为列表将在适当的位置被修改,因此它不打印任何内容。 处理:

# shuffle the list in place 
random.shuffle(b)

# print it
print(b)

如果你更喜欢函数式编程风格,你可能想要制作以下包装器函数:

def myshuffle(ls):
    random.shuffle(ls)
    return ls

你可以使用random.choices()来洗牌你的列表。

TEAMS = [A,B,C,D,E,F,G,H]
random.choices(TEAMS,k = len(TEAMS)) 

上面的代码将返回一个与前面列表相同长度的随机列表。

希望有帮助!!

可以定义一个名为shuffled的函数(与sort vs sorted意思相同)

def shuffled(x):
    import random
    y = x[:]
    random.shuffle(y)
    return y

x = shuffled([1, 2, 3, 4])
print x