我如何洗牌对象列表?我尝试了random.shuffle:

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

对于numpy(科学和金融应用程序的流行库),使用np.random.shuffle:

import numpy as np
b = np.arange(10)
np.random.shuffle(b)
print(b)

其他回答

def shuffle(_list):
    if not _list == []:
        import random
        list2 = []
        while _list != []:
            card = random.choice(_list)
            _list.remove(card)
            list2.append(card)
        while list2 != []:
            card1 = list2[0]
            list2.remove(card1)
            _list.append(card1)
        return _list

你可以这样做:

>>> 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']

如果您想返回到两个列表,那么您可以将这个长列表拆分为两个。

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

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接受任意数量的参数。所以你也可以用它洗牌三个或更多的列表。

你可以使用random.choices()来洗牌你的列表。

TEAMS = [A,B,C,D,E,F,G,H]
random.choices(TEAMS,k = len(TEAMS)) 

上面的代码将返回一个与前面列表相同长度的随机列表。

希望有帮助!!

可以定义一个名为shuffled的函数(与sort vs sorted意思相同)

def shuffled(x):
    import random
    y = x[:]
    random.shuffle(y)
    return y

x = shuffled([1, 2, 3, 4])
print x