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

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

如你所知,原地洗牌才是问题所在。我也经常有问题,经常忘记如何复制一个列表,太。使用sample(a, len(a))是解决方案,使用len(a)作为样本大小。Python文档请参见https://docs.python.org/3.6/library/random.html#random.sample。

下面是一个使用random.sample()的简单版本,它将洗牌后的结果作为一个新列表返回。

import random

a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False

# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))

try:
    random.sample(a, len(a) + 1)
except ValueError as e:
    print "Nope!", e

# print: no duplicates: True
# print: Nope! sample larger than population

其他回答

随机的。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(而不是改变后的对象)。

>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']

这对我来说很有效。确保设置了随机方法。

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

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

x = shuffled([1, 2, 3, 4])
print x
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,而是打印列表。

from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())

对于希望交换排序函数的某些应用程序,这种替代方法可能很有用。