在Python中手动随机化列表
这里有一段手动洗牌的代码。我理解到cards[pos], cards[randpos] = cards[randpos], cards[pos]
这一部分。这里发生了什么?把cards[pos]赋值给cards[randpos]有什么意义呢?
self.cards是一个按标准顺序排列的扑克牌列表。
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]
6 个回答
1
在Python中
a, b = b, a
这是交换两个变量的方法。在你的代码中,交换的是列表中位置pos
和randpos
的内容。
3
这里的 cards[pos]
和 cards[randpos]
的值正在被交换。这是一种常见的 Python 写法:你可以通过 a, b = b, a
这样的方式来交换两个或多个变量的值。
值得注意的是,标准库中洗牌的实现(random.shuffle()
)也非常相似。
0
这基本上就是在随机交换牌。它把 cards[pos]
从牌堆中拿出来,然后把 cards[randpos]
放到它的位置上,最后再把 cards[pos]
放回到 cards[randpos]
原来的地方。
另外要注意,Python 提供了一个叫 random.shuffle
的功能,这样你就不需要手动去做这些交换了。