我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
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
其他回答
你可以使用shuffle或者sample。它们都来自于随机模块。
import random
def shuffle(arr1):
n=len(arr1)
b=random.sample(arr1,n)
return b
OR
import random
def shuffle(arr1):
random.shuffle(arr1)
return arr1
如果你有多个列表,你可能想先定义排列(洗牌列表/重新排列列表中的项目的方式),然后应用到所有列表:
import random
perm = list(range(len(list_one)))
random.shuffle(perm)
list_one = [list_one[index] for index in perm]
list_two = [list_two[index] for index in perm]
努比/西皮
如果你的列表是numpy数组,它会更简单:
import numpy as np
perm = np.random.permutation(len(list_one))
list_one = list_one[perm]
list_two = list_two[perm]
mpu
我已经创建了一个小的实用程序包mpu,它有consistent_shuffle函数:
import mpu
# Necessary if you want consistent results
import random
random.seed(8)
# Define example lists
list_one = [1,2,3]
list_two = ['a', 'b', 'c']
# Call the function
list_one, list_two = mpu.consistent_shuffle(list_one, list_two)
注意mpu。Consistent_shuffle接受任意数量的参数。所以你也可以用它洗牌三个或更多的列表。
对于一行程序,使用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 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 (最后一行的傻瓜是随机排列的)
随机的。Shuffle应该可以工作。下面是一个例子,其中对象是列表:
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print(x)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
注意shuffle在原地工作,并返回None。
在Python中,更普遍的情况是,可变对象可以传递给函数,当函数改变了这些对象时,标准是返回None(而不是改变后的对象)。