提取随机数并逐步排除生成随机数的函数

2024-10-05 10:20:01 发布

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

我正在尝试做一个抽奖提取器,我需要一个脚本,提取随机数,并存储提取的那些,以避免再次提取它们。你知道吗

我想到把提取的数字存储在一个文本文件中(ToExclude.txt文件)并将该文件用作“提取”变量。你知道吗

我试着这样做但没有成功:

import random

f = open("ToExclude.txt", "r") #Opens the txt in read mode
NumToExclude = f.read() #Stores the txt file (with the previous extracted numbers)
f.close()
open("ToExclude.txt", "w").close() #Erases the content of the file

number = random.randint(1,100) #Random number generator

if number in NumToExclude: #Verifies that the number is not in the Extracted list
    [RESTART FUNCTION] #Restarts the function to generate another number
else:
    NumToExclude.append(number) #If is not in the list add the number to the lsit

print("The number is: {}".format(number)) #Example of output

f = open("ToExclude.txt", "w")  #Stores the extracted number in the txt file
f.write(str(NumToExclude))
f.close()

当我执行它时,第一个运行良好,但在第二个之后,文本文件如下所示:

['[', '5', '7', ',', ' ', '5', '7', ']', 67, 67]

Tags: 文件theintxtnumberclosereadis
3条回答

你是你想得太多了我们可以做:

all_numbers = list(range(1,101))

extracted = random.choice(all_numbers)
all_numbers.remove(extracted)

如果需要,可以循环最后两行并将值保存在列表中:

all_numbers = list(range(1,101))
result =[]
for i in range(10):
    extracted = random.choice(all_numbers)
    result.append(extracted)
    all_numbers.remove(extracted)

当你删除文件时,我想你不需要长期保存它。 可以使用集合,集合是不可变的结构,不允许重复。你知道吗

import random

lottery = set() #empty set

假设要生成6个数字:

while len(lottery) < 7:

    lottery.add(random.randint(1,100)) #same method you used for random

print(lottery)
{6, 41, 75, 49, 85, 87, 61}

如果需要多次运行,请将其放入函数中

def run_lottery():

    lottery = set()

        while len(lottery) < 7:
                lottery.add(random.randint(1,100)) #same method you used

    return lottery

并用一个变量来调用它:

  lucky = run_lottery()

  print(lucky)
  {100, 10, 13, 17, 49, 57, 63}

这里有很多问题。首先,你不能把一个列表转储到一个文本文件中,然后把它读回一个列表,这就是为什么你会有奇怪的行为。您应该查看一个名为pickle的模块。第二,正如刚才出现的另一个答案所指出的,你不需要这么复杂。从所有数字的列表开始,用random.choice()从中挑选。第三,最好在with块中打开文本文件,这样,如果出现异常,它们将被正确关闭。你知道吗

with f as open('path','r'):
 f.read()

相关问题 更多 >

    热门问题