仅随机播放列表中的最后一个元素



我正在编写一个扑克引擎,它从大量套牌中提取并创建许多手牌。我想让每手牌只包含唯一的牌,所以我在创建手牌时实施了重复检查:

def draw(self, c):
        """Generate a hand of c cards"""
        y = 0
        while y < c:
            if self.cards[-1] not in drawcards.values():
                drawcards[y] = self.cards.pop()
                y += 1
            else:
                random.shuffle(self.cards)
        return drawcards

这非常有效,除了必须反复random.shuffle(self.cards)(通常非常大(显着减慢了我的手输出。

有没有办法只洗牌我的cards列表的最后一个元素而不使用copy()(这也会对内存造成负担(?

(抽奖卡预定义为空字典(

获取不是最后一个元素的随机元素的索引:

index = random.randint(0, (len(self.cards) - 1))

然后只需切换两个元素:

self.cards[index], self.cards[-1] = self.cards[-1], self.cards[index]

如果要在列表中的随机位置插入项目,请使用 self.cards.insert(random.randint(0, len(self.cards)), card)

请注意,这样做将是 O(n(,并且具有与 random.shuffle(self.cards) 相同的运行时复杂性。

或者,您可以执行以下操作:

self.cards.append(item)
last_index = len(self.cards) - 1
random_index = random.randint(0, last_index)
# Swap elements.
self.cards[random_index], self.cards[last_index] = 
    self.cards[last_index], self.cards[random_index]

这应该比插入列表中间更快。 但是,这可能会让人感到有问题,因为它涉及将其他一些卡移动到末尾。(但由于甲板应该被洗牌,所以实际上并不重要。

最新更新