我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
当前回答
你可以这样做:
>>> A = ['r','a','n','d','o','m']
>>> B = [1,2,3,4,5,6]
>>> import random
>>> random.sample(A+B, len(A+B))
[3, 'r', 4, 'n', 6, 5, 'm', 2, 1, 'a', 'o', 'd']
如果您想返回到两个列表,那么您可以将这个长列表拆分为两个。
其他回答
#!/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]
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']
这对我来说很有效。确保设置了随机方法。
计划:写出shuffle而不依赖于库来做繁重的工作。示例:从元素0开始从头遍历列表;为它找一个新的随机位置,比如6,把0的值放到6,把6的值放到0。移动到元素1并重复此过程,如此循环到列表的其余部分
import random
iteration = random.randint(2, 100)
temp_var = 0
while iteration > 0:
for i in range(1, len(my_list)): # have to use range with len()
for j in range(1, len(my_list) - i):
# Using temp_var as my place holder so I don't lose values
temp_var = my_list[i]
my_list[i] = my_list[j]
my_list[j] = temp_var
iteration -= 1
如你所知,原地洗牌才是问题所在。我也经常有问题,经常忘记如何复制一个列表,太。使用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
它工作得很好。我在这里尝试用函数作为列表对象:
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 (最后一行的傻瓜是随机排列的)