【发布时间】:2019-11-06 14:37:13
【问题描述】:
我正在尝试做一个彩票提取器,我需要一个脚本来提取随机数并存储提取的随机数以不再提取它们。
我想出了将提取的数字存储在文本文件 (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]
【问题讨论】:
-
random.sample(range(100),x )将返回x未被替换的随机数。 -
random.sample(range(1,100),x) 与问题中相同的数字(从 1 到 99)
-
NumToExclude = f.read()将文本字符串放入 NumToExclude,但您需要一个数字列表 -
NumToExclude= [ast.literal_eval(line.strip()) for line in f]` 如stackoverflow.com/questions/33351770/…
-
随机播放您的号码列表,然后从随机播放的列表中选择您想要的号码。这保证没有重复,前提是初始列表没有重复。
标签: python python-3.x random