我正在尝试做一个抽奖提取器,我需要一个脚本,提取随机数,并存储提取的那些,以避免再次提取它们。你知道吗
我想到把提取的数字存储在一个文本文件中(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]
你是你想得太多了我们可以做:
如果需要,可以循环最后两行并将值保存在列表中:
当你删除文件时,我想你不需要长期保存它。 可以使用集合,集合是不可变的结构,不允许重复。你知道吗
假设要生成6个数字:
如果需要多次运行,请将其放入函数中
并用一个变量来调用它:
这里有很多问题。首先,你不能把一个列表转储到一个文本文件中,然后把它读回一个列表,这就是为什么你会有奇怪的行为。您应该查看一个名为pickle的模块。第二,正如刚才出现的另一个答案所指出的,你不需要这么复杂。从所有数字的列表开始,用
random.choice()
从中挑选。第三,最好在with块中打开文本文件,这样,如果出现异常,它们将被正确关闭。你知道吗相关问题 更多 >
编程相关推荐