我如何洗牌对象列表?我尝试了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())

对于希望交换排序函数的某些应用程序,这种替代方法可能很有用。

其他回答

如果你有多个列表,你可能想先定义排列(洗牌列表/重新排列列表中的项目的方式),然后应用到所有列表:

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

你可以构建一个函数,以一个列表作为参数,并返回一个打乱的列表版本:

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

洗牌过程是“带替换”的,所以每一项的出现都可能发生变化!至少当项目在你的列表时也是列表。

例如,

ml = [[0], [1]] * 10

之后,

random.shuffle(ml)

[0]的数字可能是9或8,但不完全是10。

""" 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