只打乱列表的最后一个元素
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)
(通常非常大)会显着降低我的手输出速度之外,这非常有效。
有没有办法在不使用 copy()
的情况下只打乱 cards
列表的最后一个元素(这也会占用内存)?
(drawcards 预定义为空字典)
如果您想在列表中的随机位置插入一个项目,请使用 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]
我正在编写一个扑克引擎,它可以从大量的牌组中抽取并创建很多手牌。我想让每手牌只包含唯一的牌,所以我在创建手牌时实施了重复检查:
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)
(通常非常大)会显着降低我的手输出速度之外,这非常有效。
有没有办法在不使用 copy()
的情况下只打乱 cards
列表的最后一个元素(这也会占用内存)?
(drawcards 预定义为空字典)
如果您想在列表中的随机位置插入一个项目,请使用 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]