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

import random

b = [object(), object()]

print(random.shuffle(b))

但它输出:

None

当前回答

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

其他回答

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

如你所知,原地洗牌才是问题所在。我也经常有问题,经常忘记如何复制一个列表,太。使用sample(a, len(a))是解决方案,使用len(a)作为样本大小。Python文档请参见https://docs.python.org/3.6/library/random.html#random.sample。

下面是一个使用random.sample()的简单版本,它将洗牌后的结果作为一个新列表返回。

import random

a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False

# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))

try:
    random.sample(a, len(a) + 1)
except ValueError as e:
    print "Nope!", e

# print: no duplicates: True
# print: Nope! sample larger than population

如果你需要一个原地洗牌和操作种子的能力,这段代码会有帮助:

from random import randint

a = ['hi','world','cat','dog']
print(sorted(a, key=lambda _: randint(0, 1)))

记住,“洗牌”是一种随机键排序。

随机的。Shuffle应该可以工作。下面是一个例子,其中对象是列表:

from random import shuffle

x = [[i] for i in range(10)]
shuffle(x)
print(x)

# print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]

注意shuffle在原地工作,并返回None。

在Python中,更普遍的情况是,可变对象可以传递给函数,当函数改变了这些对象时,标准是返回None(而不是改变后的对象)。

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