开发者

randomizing a list in python manually

Here's some code for shuffling a deck of cards manually. I understan开发者_开发百科d it up to the point where cards[pos], cards[randpos] = cards[randpos], cards[pos]. What is happening here? What is the point of assigning cards[pos] to cards[randpos]?

self.cards is a list of playing cards in standard order.

  def shuffle(self):
        n = len(self.cards)
        cards = self.cards
        for pos in range(n):
            randpos = randrange(pos,n)
            cards[pos], cards[randpos] = cards[randpos], cards[pos]


The values of cards[pos] and cards[randpos] are being switched. This is a common Python idiom: you can switch two or more variables' values by saying a, b = b, a.

Note that the standard library implementation of shuffling (random.shuffle()) is quite similar.


It's swapping the positions of the cards in pos and randpos.

So, for example, if your list were [1,2,3,4,5,6,7] and pos were 0, first it would pick an index that comes after the 1 in the list. Then it would swap the 1 and the number at that index. So if randpos is 3 on the first iteration, we end up with [4,2,3,1,5,6,7] after one time through the loop.

As a side note, it is much more efficient (and reliable) to use random.shuffle().


In python

a, b = b, a

is how you swap two variables. In your code what are swapped are the contents of the list at position pos and randpos.


cards[pos], cards[randpos] = cards[randpos], cards[pos]

This is simply swapping cards[pos] and cards[randpos]

Here's an entire Web page on the technique: http://blog.mithis.net/archives/ideas/64-python-swap-var


cards[pos], cards[randpos] = cards[randpos], cards[pos]

Is swapping the card at index pos with the card at index randpos

It's basically assigning card[randpos] to card[pos] and card[pos] to card[randpos]. Another way to do it would be

t = card[pos]
card[pos] = card[randpos]
card[randpos] = t

The former is just shorter and more pythonic.


It's basically randomly swapping cards. It's taking cards[pos] out of the deck, placing cards[randpos] at its location, and placing cards[pos] back at where cards[randpos] was.

Also note, that Python provides random.shuffle so that you don't have to do this manually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜