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

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

你可以使用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

其他回答

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

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

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

希望有帮助!!

如果你有多个列表,你可能想先定义排列(洗牌列表/重新排列列表中的项目的方式),然后应用到所有列表:

import random

perm = list(range(len(list_one)))
random.shuffle(perm)
list_one = [list_one[index] for index in perm]
list_two = [list_two[index] for index in perm]

努比/西皮

如果你的列表是numpy数组,它会更简单:

import numpy as np

perm = np.random.permutation(len(list_one))
list_one = list_one[perm]
list_two = list_two[perm]

mpu

我已经创建了一个小的实用程序包mpu,它有consistent_shuffle函数:

import mpu

# Necessary if you want consistent results
import random
random.seed(8)

# Define example lists
list_one = [1,2,3]
list_two = ['a', 'b', 'c']

# Call the function
list_one, list_two = mpu.consistent_shuffle(list_one, list_two)

注意mpu。Consistent_shuffle接受任意数量的参数。所以你也可以用它洗牌三个或更多的列表。

#!/usr/bin/python3

import random

s=list(range(5))
random.shuffle(s) # << shuffle before print or assignment
print(s)

# print: [2, 4, 1, 3, 0]
import random
class a:
    foo = "bar"

a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)

它工作得很好。我在这里尝试用函数作为列表对象:

    from random import shuffle

    def foo1():
        print "foo1",

    def foo2():
        print "foo2",

    def foo3():
        print "foo3",

    A=[foo1,foo2,foo3]

    for x in A:
        x()

    print "\r"

    shuffle(A)
    for y in A:
        y()

它打印出: Foo1 foo2 foo3 Foo2 foo3 foo1 (最后一行的傻瓜是随机排列的)