我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
当前回答
from random import random
my_list = range(10)
shuffled_list = sorted(my_list, key=lambda x: random())
对于希望交换排序函数的某些应用程序,这种替代方法可能很有用。
其他回答
洗牌过程是“带替换”的,所以每一项的出现都可能发生变化!至少当项目在你的列表时也是列表。
例如,
ml = [[0], [1]] * 10
之后,
random.shuffle(ml)
[0]的数字可能是9或8,但不完全是10。
在某些情况下,当使用numpy数组时,使用random。Shuffle在数组中创建了重复数据。
另一种方法是使用numpy.random.shuffle。如果您已经在使用numpy,这是通用random.shuffle的首选方法。
numpy.random.shuffle
例子
>>> import numpy as np
>>> import random
使用random.shuffle:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[1, 2, 3],
[4, 5, 6]])
使用numpy.random.shuffle:
>>> foo = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> foo
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.random.shuffle(foo)
>>> foo
array([[1, 2, 3],
[7, 8, 9],
[4, 5, 6]])
#!/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']
这对我来说很有效。确保设置了随机方法。
对于numpy(科学和金融应用程序的流行库),使用np.random.shuffle:
import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)