[英]How to shuffle a list in Python
def make_sorted_deck():
''' Return a sorted deck of cards. Each card is
represented by a string as follows:
"queen of hearts". The cards are ordered by rank and then suit within rank.
:return: The sorted deck of cards, as a list of strings
EXAMPLE: make_sorted_deck() == ['2 of spades', '2 of hearts', '2 of clubs', ..., 'ace of clubs', 'ace of diamonds'] '''
#Hint: Use the previous functions and two nested for loops.
sorted_deck = []
for i in get_ranks():
for j in get_suits():
sorted_deck.append("{0} of {1}".format(i,j))
return sorted_deck
print(make_sorted_deck())
def shuffle(deck):
''' Randomly shuffle the cards in deck into a newly created deck of cards (list).
:param: deck: A deck of cards
:return: A new list, consisting of a random shuffle of deck.
EXAMPLE: shuffle(['2 of hearts', '3 of diamonds', 'jack of spades', '2 of clubs']) could return ['jack of spades', '3 of diamonds', '2 of hearts', '2 of clubs']
#REQUIREMENTS: Please implement the following algorithm: Use a while loop to repeatedly pick a random card from deck, remove it, and add it to a newly created list. '''
我如何洗牌make_sorted_deck()
創建的列表?
我知道我可以導入一個隨機播放卡組的功能,但是我需要這樣做的方法是取出1張隨機卡並將其附加到新列表中以產生隨機播放的列表。
另一個不能回答OP問題的答案...
要隨機排列長度為n
的列表,您需要一個索引列表,從0
到n-1
,以隨機順序...
我們開始從random
模塊導入randrange
函數,
from random import randrange
這樣調用randrange(n)
返回一個隨機整數i
, 0 <= i <= n-1
。
當我們選擇第一個隨機索引(包括0
到n-1
,我們將以較窄的間隔選擇下一個索引,依此類推……
l = [randrange(n-i) for i in range(n)]
當然, l
的最后一個數字將為0
因為i==n-1
並且randrange(1)
必須返回0
。
l
的數字不能直接用於尋址要改組的列表,因為它們指的是改組過程中特定點在可用元素列表中的位置,因此對於n中的每個數字,我們必須查看有多少個元素具有已經改組,它們相對於當前元素的位置,假設我們要將_real_indices存儲在一個列表中,最初為空
indices = []
我們必須要小心...
for i in l: # the randomized, partial indices
j = 0 # aux variable
while j <= i: # we will increment j later
if j in indices: # if this number j, smaller than i, is in the
i += 1 # list of used indices, i must be incremented
j += 1
indices.append(i) # the (possibly) incremented i is stored
這就是洗牌。
在這里,我報告了一個簡短的IPython會話,演示了這種方法的正確性:
In [1]: from random import randrange
In [2]: def shuffle(n):
l = [randrange(n-i) for i in range(n)]
indices = []
for i in l:
j = 0
while j <= i:
if j in indices: i = i+1
j = j+1
indices.append(i)
return indices
...:
In [3]: sh = shuffle(10) ; print sh ; print sorted(sh)
[7, 6, 4, 9, 1, 5, 0, 2, 8, 3]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [4]: sh = shuffle(10) ; print sh ; print sorted(sh)
[6, 9, 5, 1, 4, 3, 0, 2, 8, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [5]: sh = shuffle(10) ; print sh ; print sorted(sh)
[3, 6, 4, 9, 0, 7, 8, 1, 2, 5]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [6]:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.