【发布时间】:2019-06-02 19:23:25
【问题描述】:
实际上,我正在制作一个随机数猜谜游戏,我必须从用户那里获取 50 个数字的输入,然后将它们存储在一个文件中,然后从文件中读取这些数字,然后从这些数字中随机选择任何 25 个数字然后在 5x5 网格中显示它们,我也有更多要求,但我已经为它们完成了所有编码,但我面临的问题是我不知道如何从文件中读取这些数字并将它们存储在一个数组中或以整数形式列出。
import numpy
from random import sample
f = open("Python_Project.txt","w+")
count = 0
print("Enter 20 unique numbers within the range 1-100")
while (count<20):
x = int(input())
if x > 0 and x < 101:
f.write(str(x))
f.write(" ")
count += 1
else:
print("Please Enter a number between the range")
f.close()
myfile = open("Python_Project.txt", "r")
contents = myfile.read().split(',')
myfile.close()
print(contents)
['12 23 54 3 8 35 33 76 98 55 6 8 3 12 43 56 65 33 78 89 '] 我得到了这个,但我需要这些数字作为整数,以便我可以对它们进行排序并做其他事情
【问题讨论】:
-
你为什么要写数字空格分隔并用逗号分割它们?
-
https://stackoverflow.com/questions/21285684/how-to-read-numbers-in-text-file-using-python - https://stackoverflow.com/questions/12271503/python-read-numbers-from-text-file-and-put-into-list - https://stackoverflow.com/questions/25812578/trying-to-read-a-txt-file-with-numbers-into-a-list (forget the sorting part)
标签: python python-3.x