Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python从文本文件中读取矩阵_Python_Arrays_Matrix_Text - Fatal编程技术网

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

用Python从文本文件中读取矩阵,python,arrays,matrix,text,Python,Arrays,Matrix,Text,我试图从一个给定的文本文件中读取一个矩阵,把它放在字典中,然后再对它进行操作,但是当我试图访问元素时,“,”显示为一个元素,它真的把我的索引搞砸了 我尝试过使用split函数,它看起来读起来很好,但是“,”仍然作为一个元素出现 def loadboard(): f = open("game.txt", "r") A=f.readline() B=f.readline() C=f.readline() board=[] board = [[int(n

我试图从一个给定的文本文件中读取一个矩阵,把它放在字典中,然后再对它进行操作,但是当我试图访问元素时,“,”显示为一个元素,它真的把我的索引搞砸了

我尝试过使用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]: ','
试试这个:

with open('game.txt', 'r') as f:
    l = [[int(num) for num in line.split(',')] for line in f]
print(l)
这将有助于:

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

print(matrix)
这对我来说很有效:

    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

嘿,问题是我的文本文件在矩阵上面已经有3行了,这是我事先读过的,所以我认为我不能使用你的方法。我会更新代码以便你们能看到。编辑:修复,谢谢大家!