除列表b中的数字外的随机数

2024-03-28 09:10:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何得到从7到14的随机数,但是也有可能得到从7到14的随机数,除了以前写的列表中的一些数字之外?你知道吗

示例:

Forbidden = [12, 13, 8, 7]
a = randint(7, 14) 

a应该是一个随机数,但不是Forbidden中写的数。你知道吗

编辑:谢谢你的建议,使用while循环或choice。实际上解决了我的问题。但最后@user2357112是对的,显然黑名单的想法是一个初学者的陷阱,洗牌一副牌解决了我的问题。你知道吗


Tags: 编辑示例列表数字建议陷阱randintchoice
3条回答

您可以使用choice函数:

import random
total_data = [i for i in range(1,15)]
forbidden = [12, 13, 8, 7]
not_forbidden =[i for i in total_data if i not in forbidden] #make a list of not forbidden numbers
a = random.choice(not_forbidden) #select value which is between 7 and 14 and not in forbidden list
print(a)

也可以编写自己的自定义函数:

import random
Forbidden = [12, 13, 8, 7]
def get_number(forbidden_list):
    while True:
        a = random.randint(7,14)
        if a not in forbidden_list: #if this number if not forbidden list then break the loop and return the value
            return a
result = get_number(Forbidden)
print(result)

你可以试试random.choice()

import random
...
not_forbidden = [1,2,3,4]
a = random.choice(not_forbidden)

你知道一个真正的纸牌游戏如何阻止你抽已经抽过的牌吗?不涉及抽牌黑名单。有一副牌,你洗牌。你知道吗

在你的程序中做同样的事情。与其试图维持抽牌的黑名单,不如在程序开始时洗牌一副牌,然后从牌堆中抽牌:

import random

deck = some_list
random.shuffle(deck)

# when you want to draw a card
card = deck.pop()

相关问题 更多 >