繁体   English   中英

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

[英]Shuffle only the last element of a list

我正在编写一个扑克引擎,该引擎可以从大量牌组中抽出并创造出很多手牌。 我想让每只手只包含唯一的卡片,因此在创建手时实施了重复检查:

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()这也将内存征税)?

(将抽奖卡预先定义为空字典)

如果要在列表中的任意位置插入项目,请使用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]

这应该比插入列表中间要快。 但是,由于涉及将其他卡移动到末尾,因此可能会令人感到怀疑。 (但是,由于应该对甲板进行了改组,因此实际上并不重要。)

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

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

然后只需切换两个元素:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM