在Python中从文本文件读取矩阵

时间:2019-05-07 08:07:42

标签: python arrays matrix text

我正在尝试从给定的文本文件中读取矩阵,将其放入字典中,然后再进行操作,但是,当我尝试访问元素时,“,”显示为元素,这确实弄乱了我的索引编制

我尝试使用split函数,看起来似乎读起来不错,但是','仍然作为元素出现

def loadboard():
    f = open("game.txt", "r")
    A=f.readline()
    B=f.readline()
    C=f.readline()
    board=[]
    board = [[int(num) for num in line.split(',')] for line in f]
    print(board)
    game = {
            "player1" : A,
            "player2" :B,
            "who" : C,
            "board" : board
            }  
    f.close()
    return(game)

这是我的文本文件

A
B
C
0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0
0,0,1,2,1,0,0,0
0,0,1,2,2,2,0,0
0,0,1,2,1,0,0,0
0,0,0,2,1,0,0,0
0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0

这是我在印制板时看到的

Out[242]: 
['0,0,0,0,0,0,0,0\n',
 '0,0,0,0,0,0,0,0 \n',
 '0,0,1,2,1,0,0,0 \n',
 '0,0,1,2,2,2,0,0\n',
 '0,0,1,2,1,0,0,0 \n',
 '0,0,0,2,1,0,0,0\n',
 '0,0,0,0,0,0,0,0\n',
 '0,0,0,0,0,0,0,0']

当我尝试访问第二个应该再次为零的元素时,我得到','

board[0][1]
Out[243]: ','

3 个答案:

答案 0 :(得分:1)

这对我来说很好:

    board = []
    with open('toto.txt', 'r') as f:
        for row in f.read().strip().split("\n")[3:]:
            board.append(row.split(","))
    for line in board:
        print (line)
    print "board[0] : " + str(board[0])
    print "board[0][1] : " + str(board[0][1])

输出:

(venv) C:\Users\hlupo\Documents\SoTest>python test.py
['0', '0', '0', '0', '0', '0', '0', '0']
['0', '0', '0', '0', '0', '0', '0', '0']
['0', '0', '1', '2', '1', '0', '0', '0']
['0', '0', '1', '2', '2', '2', '0', '0']
['0', '0', '1', '2', '1', '0', '0', '0']
['0', '0', '0', '2', '1', '0', '0', '0']
['0', '0', '0', '0', '0', '0', '0', '0']
['0', '0', '0', '0', '0', '0', '0', '0']
board[0] : ['0', '0', '0', '0', '0', '0', '0', '0']
board[0][1] : 0

答案 1 :(得分:0)

尝试一下:

ArgumentParser.parse_args

答案 2 :(得分:0)

这可以做到:

matrix = []
with open('game.txt','r') as f:
    for row in f.read().strip().split("\n")[3:]:
        matrix.append(row.split(","))

print(matrix)