任何人都可以尝试帮助我在 Python 中检索数字并将每个数字存储到数组中: 我已经完成了以下代码,它完成了工作,但将 10 读为两个数字:
with open("test.dat") as infile:
for i, line in enumerate(infile):
if i == 0:
for x in range(0, len(line)):
if(line[x] == ' ' or line[x] == " "):
continue
else:
print(x, " " , line[x], ", ")
initial_state.append(line[x])
---结果:
(0, ' ', '1', ', ')
(2, ' ', '2', ', ')
(4, ' ', '3', ', ')
(6, ' ', '4', ', ')
(8, ' ', '5', ', ')
(10, ' ', '6', ', ')
(12, ' ', '7', ', ')
(14, ' ', '8', ', ')
(16, ' ', '9', ', ')
(18, ' ', '1', ', ')
(19, ' ', '0', ', ')
(21, ' ', '1', ', ')
(22, ' ', '1', ', ')
(24, ' ', '1', ', ')
(25, ' ', '2', ', ')
(27, ' ', '1', ', ')
(28, ' ', '3', ', ')
(30, ' ', '1', ', ')
(31, ' ', '4', ', ')
(33, ' ', '1', ', ')
(34, ' ', '5', ', ')
(36, ' ', '0', ', ')
(37, ' ', '\n', ', ')
索引包含空格,请查看我尝试添加到数组的数字行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0
最佳答案
使用.split()通过循环来分割所有字段,请看下面的代码,应该可以做到
with open("test.dat") as infile:
for i, line in enumerate(infile):
if i == 0: # if first line
field = [field.split(" ") for field in line.split(" ")]
for x in range(0, len(field)):
initial_state_arr.append(field[x])
关于python-2.7 - 如何使用python2.7从文本文件读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334722/