从文件中读取数值并将其放置为数组

时间:2018-12-13 21:29:57

标签: python arrays python-2.7

我有一个像这样的文本文件

.txt

1, 2, 3, 4, 5, 6, 7, 8, 9

我想将其视为python中的数组,这是我到目前为止所拥有的

python文件

 file_board = open('index.txt')
 board = file_board.read().split(',')
 print board
 print len(board)

输出

['[[1', ' 2', ' 3]', ' [4', ' 5', ' 6]', ' [7', ' 8', ' 9]]\n']
9
list index out of range

所以我想做的是一些如何将其放入2D数组中进行操作

注意,我想在没有任何外部库的情况下执行此操作,内置库很好

顺便说一句,我想写回一个新文件

的格式
1, 2, 3, 4, 5, 6, 7, 8, 9

1 个答案:

答案 0 :(得分:1)

您可以使用索引切片和zip来做到这一点:

infile = open('./Desktop/nums.txt')

board = infile.read().strip('\\n').split(',')
# the numbers are in string format at this point
# board ['1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9']
board_array = [[int(x),int(y),int(z)] for x,y,z in zip(board[::3], board[1::3], board[2::3])]

输出:

>>> board_array
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

我不明白您希望从输出中得到什么,但是这将从文本文件中生成一个整数数组,并会去除该换行符'\n'

相关问题