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

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

对于一行程序,使用userandom。示例(list_to_be_shuffled, length_of_the_list)与示例:

import random
random.sample(list(range(10)), 10)

输出: [2,9,7,8,3,0,4,1,6,5]

其他回答

如你所知,原地洗牌才是问题所在。我也经常有问题,经常忘记如何复制一个列表,太。使用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']

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

文档为随机。Shuffle声明它会

打乱序列x的位置。

不要做:

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

相反,做:

random.shuffle(xs)
print(xs)

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

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

对于一行程序,使用userandom。示例(list_to_be_shuffled, length_of_the_list)与示例:

import random
random.sample(list(range(10)), 10)

输出: [2,9,7,8,3,0,4,1,6,5]