洗牌对象列表
  我有一个在Python中的对象列表,我想打乱他们。  我想我可以使用random.shuffle方法,但是当列表是对象时,这似乎失败了。  有没有一种方法来洗牌或其他方式? 
import random
class a:
    foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print random.shuffle(b)
这将失败。
  random.shuffle应该可以工作。  以下是一个示例,其中的对象是列表: 
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
# print x  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary
请注意,洗牌工作到位 ,并返回无。
  正如你所了解的,就地洗牌是个问题。  我也经常遇到问题,而且往往似乎忘记了如何复制列表。  使用sample(a, len(a))是解决方案,使用len(a)作为样本大小。  请参阅https://docs.python.org/3.6/library/random.html#random.sample Python文档。 
  这是一个使用random.sample()的简单版本, 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
#!/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]
上一篇: Shuffling a list of objects
下一篇: Best way to define private methods for a class in Objective
