【问题标题】:How to read numbers that are stored in a text file and then store them in a list or array as integers如何读取存储在文本文件中的数字,然后将它们作为整数存储在列表或数组中
【发布时间】: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 '] 我得到了这个,但我需要这些数字作为整数,以便我可以对它们进行排序并做其他事情

【问题讨论】:

标签: python python-3.x


【解决方案1】:
new_content = []
for i in contents[0].split(" "):
    try:
        new_content.append(int(i))
    except ValueError:
        continue
print(new_content)

将此代码添加到文件的最后。 这里 new_content 是整数数组。 仅当您在代码中使用空格而不是逗号进行拆分时,此代码才会按预期工作

【讨论】:

  • 谢谢兄弟,但我最后尝试了这段代码,它只打印第一个索引值而不是整个列表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-05
  • 2021-06-09
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 2021-10-03
相关资源
最近更新 更多