Python从头开始洗牌

Python从头开始洗牌,python,python-3.x,Python,Python 3.x,我正在编写一个函数来创建一个新的无序列表(我不能使用内置的无序函数) 这就是我现在拥有的,它正在工作,但是当我返回洗牌列表时,列表中有重复的元素。如何使函数只返回列表中的元素一次 与下一个类似(未测试) 您可能会发现这种洗牌实现适合您的需要。在使用这两个函数之前,请务必注意它们之间的差异 >>> import random >>> def shuffle(array): copy = list(array) shuffle_in_place(c

我正在编写一个函数来创建一个新的无序列表(我不能使用内置的无序函数)

这就是我现在拥有的,它正在工作,但是当我返回洗牌列表时,列表中有重复的元素。如何使函数只返回列表中的元素一次

与下一个类似(未测试)


您可能会发现这种洗牌实现适合您的需要。在使用这两个函数之前,请务必注意它们之间的差异

>>> import random
>>> def shuffle(array):
    copy = list(array)
    shuffle_in_place(copy)
    return copy

>>> def shuffle_in_place(array):
    array_len = len(array)
    assert array_len > 2, 'Array is too short to shuffle!'
    for index in range(array_len):
        swap = random.randrange(array_len - 1)
        swap += swap >= index
        array[index], array[swap] = array[swap], array[index]


>>> array = list(range(10))
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle(array)
[7, 2, 3, 5, 8, 6, 0, 1, 9, 4]
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle_in_place(array)
>>> array
[8, 3, 1, 6, 9, 7, 0, 4, 2, 5]
>>> 

正如您所发现的那样,抽样有可能多次选择同一个项目。而不是采样,你可以考虑交换作为战略。洗牌不洗牌,这听起来很像家庭作业…@纪尧姆+ 1可疑作业。不过,有些事情我们可以给你一些指导。首先,如果可以避免,请不要在函数中导入模块。其次,尝试探索Python提供的关键内置数据结构,您可能会对1感到惊讶。解决这个问题有多容易2。有多少方法可以解决这个问题。谷歌“Fisher-Yates”可能是
from random import choice

def get_list( l ):
    len_ = len( l )
    output = []

    for i in range( len_ ):
        index = choice( len( l ) )
        output.append( l[ index ] )
        del l[ index ]

    return output
>>> import random
>>> def shuffle(array):
    copy = list(array)
    shuffle_in_place(copy)
    return copy

>>> def shuffle_in_place(array):
    array_len = len(array)
    assert array_len > 2, 'Array is too short to shuffle!'
    for index in range(array_len):
        swap = random.randrange(array_len - 1)
        swap += swap >= index
        array[index], array[swap] = array[swap], array[index]


>>> array = list(range(10))
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle(array)
[7, 2, 3, 5, 8, 6, 0, 1, 9, 4]
>>> array
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> shuffle_in_place(array)
>>> array
[8, 3, 1, 6, 9, 7, 0, 4, 2, 5]
>>>