我如何洗牌对象列表?我尝试了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,而是打印列表。

其他回答

如你所知,原地洗牌才是问题所在。我也经常有问题,经常忘记如何复制一个列表,太。使用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
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']

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

洗牌过程是“带替换”的,所以每一项的出现都可能发生变化!至少当项目在你的列表时也是列表。

例如,

ml = [[0], [1]] * 10

之后,

random.shuffle(ml)

[0]的数字可能是9或8,但不完全是10。

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

    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 (最后一行的傻瓜是随机排列的)

对于numpy(科学和金融应用程序的流行库),使用np.random.shuffle:

import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)