Skip to main content
 首页 » 编程设计

python之在不使用另一个列表中的数字的情况下在 python 中创建随机数列表

2025年05月04日10davidwang456

我正在尝试制作纸牌游戏,我希望能够在列表中生成随机数,但我不希望这些数字在程序运行时使用一次后重复出现。

这是我目前所拥有的:

usedcards = [] 
import random 
 
def choosecards(): 
    global usedcards 
    cards=random.sample(range(52), 5) 
    usedcards = usedcards + cards 
    #print(usedcards) 
    return cards 

每次运行该函数时,我都希望使用 cards 变量交叉检查 usedcards 列表。

我怎样才能做到这一点?

请您参考如下方法:

这是使用集合执行此操作的一种方法。集合可以很容易地排除已经使用过的卡片。

import random 
 
used_cards = set() 
 
def choose_cards(n_cards): 
    # No need to do 'global used_cards', used_cards is 
    #    already global and can be modified inplace 
    # Find the set difference between all the cards and 
    #   those that have been used 
    available = set(range(52)) - used_cards 
    chosen = random.sample(available, n_cards) 
    for card in chosen: 
        used_cards.add(card) 
    return chosen 
 
 
for i in range(4): 
    print(choose_cards(5)) 
    print(used_cards)