我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
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
其他回答
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,而是打印列表。
可以定义一个名为shuffled的函数(与sort vs sorted意思相同)
def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
如你所知,原地洗牌才是问题所在。我也经常有问题,经常忘记如何复制一个列表,太。使用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
对于一行程序,使用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]
你可以构建一个函数,以一个列表作为参数,并返回一个打乱的列表版本:
from random import *
def listshuffler(inputlist):
for i in range(len(inputlist)):
swap = randint(0,len(inputlist)-1)
temp = inputlist[swap]
inputlist[swap] = inputlist[i]
inputlist[i] = temp
return inputlist