当循环嵌套在if条件中时,请帮我处理这个问题



我正试图从17个数字中提取一定数量的数字。但是,如果一个数字无效(由用户决定(,我需要提取另一个与无效数字和已提取的数字不同的唯一节点。这是我的代码:

import random
import rich
from rich.console import Console
console = Console()
num = int(console.input('[yellow]How many number you want to extract[/yellow]: '))
non = int(console.input('[yellow]Number you want to exclude[/yellow]: '))
x = random.sample(range(1,18),num)
console.print("[yellow]Numbers extracted: [/yellow]",str(x))
for i in x:
if i == 1:
if non != 1:
console.print('[green]:heavy_check_mark:[/green] Baiesi')
else:
console.print('❌ Baiesi')
riserva = random.sample(range(1,18),1)
notvalid = True
while notvalid:
if i not in riserva or x[i] not in riserva:
sosti = random.sample(range(1,18),1)
print(sosti)
notvalid = False
else:
notvalid = True
print('unique nuber not valid')
#copy the code written before for every number until 17

这个代码的问题是,应该提取的唯一数字不是唯一的:有时它会给出已经提取的数字。有人知道怎么做吗?

您的解决方案太复杂了。只需创建数字列表,从中删除禁止的数字并提取样本:

num = int(console.input('[yellow]How many number you want to extract[/yellow]: '))
non = int(console.input('[yellow]Number you want to exclude[/yellow]: '))
nums = list(range(1,18)
nums.remove(non)
x = random.sample(nums, num)
for i in x:
console.print('[green]:heavy_check_mark:[/green] Baiesi')

最新更新