簡體   English   中英

從零開始的Python Shuffle

[英]Python Shuffle from scratch

我正在編寫一個將創建新的隨機播放列表的函數(我無法使用內置的隨機播放函數)

def Shuf(aList):

  import random
  newList=[]
  for i in range(len(aList)):
      element=random.sample(aList,1)
      newList+=element
  return newList

這就是我現在所擁有的,並且可以正常工作,但是當我返回經過改組的列表時,列表中有重復的元素。 如何使函數一次只返回列表中的元素?

類似於下一個(未經測試)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM