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

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
a3 = a()
a4 = a()
b = [a1,a2,a3,a4]

random.shuffle(b)
print(b)

shuffle已经到位,所以不打印结果,结果为None,而是打印列表。

其他回答

'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

在某些情况下,当使用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]])

随机的。Shuffle应该可以工作。下面是一个例子,其中对象是列表:

from random import shuffle

x = [[i] for i in range(10)]
shuffle(x)
print(x)

# print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]

注意shuffle在原地工作,并返回None。

在Python中,更普遍的情况是,可变对象可以传递给函数,当函数改变了这些对象时,标准是返回None(而不是改变后的对象)。

def shuffle(_list):
    if not _list == []:
        import random
        list2 = []
        while _list != []:
            card = random.choice(_list)
            _list.remove(card)
            list2.append(card)
        while list2 != []:
            card1 = list2[0]
            list2.remove(card1)
            _list.append(card1)
        return _list

文档为随机。Shuffle声明它会

打乱序列x的位置。

不要做:

print(random.shuffle(xs))  # WRONG!

相反,做:

random.shuffle(xs)
print(xs)