我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
我如何洗牌对象列表?我尝试了random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
但它输出:
None
当前回答
计划:写出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
其他回答
""" to shuffle random, set random= True """
def shuffle(x,random=False):
shuffled = []
ma = x
if random == True:
rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
return rando
if random == False:
for i in range(len(ma)):
ave = len(ma)//3
if i < ave:
shuffled.append(ma[i+ave])
else:
shuffled.append(ma[i-ave])
return shuffled
如果你有多个列表,你可能想先定义排列(洗牌列表/重新排列列表中的项目的方式),然后应用到所有列表:
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接受任意数量的参数。所以你也可以用它洗牌三个或更多的列表。
可以定义一个名为shuffled的函数(与sort vs sorted意思相同)
def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
确保您没有将源文件命名为random.py,并且在您的工作目录中没有一个名为random.pyc的文件。这两种情况都可能导致程序尝试导入本地random.py文件,而不是python的random模块。
如果你需要一个原地洗牌和操作种子的能力,这段代码会有帮助:
from random import randint
a = ['hi','world','cat','dog']
print(sorted(a, key=lambda _: randint(0, 1)))
记住,“洗牌”是一种随机键排序。