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

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

'print func(foo)'将在使用'foo'调用时打印'func'的返回值。 然而,'shuffle'的返回类型是None,因为列表将在适当的位置被修改,因此它不打印任何内容。 处理:

# shuffle the list in place 
random.shuffle(b)

# print it
print(b)

如果你更喜欢函数式编程风格,你可能想要制作以下包装器函数:

def myshuffle(ls):
    random.shuffle(ls)
    return ls

其他回答

在某些情况下,当使用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]])
import random

class a:
    foo = "bar"

a1 = a()
a2 = a()
a3 = a()
a4 = a()
b = [a1,a2,a3,a4]

random.shuffle(b)
print(b)

shuffle已经到位,所以不打印结果,结果为None,而是打印列表。

对于一行程序,使用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]

#!/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]

你可以这样做:

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

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