简体   繁体   English

从 Python 中的一行 txt 文件创建二维数组

[英]Creating a 2D array from a one line txt file in Python

I'm attempting to read a one line text file into an array in python, but I am struggling with actually getting the file to transform into an 2D array.我试图将单行文本文件读入 python 中的数组,但我正在努力将文件转换为二维数组。 This is the text file:这是文本文件:

6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0

The first number (6) represents the columns and the second number (4) represents the rows.第一个数字 (6) 代表列,第二个数字 (4) 代表行。 Here is the code I have so far:这是我到目前为止的代码:

maze_1d_arr = open(sys.argv[1], 'r')

    maze = []

    maze_split = np.array([maze_1d_arr])

    size_X = len(maze_split)
    size_Y = len(maze_split[0])

    maze_grid = [int(x) for x in maze_split[2:]]

    maze = np.array(maze_grid).reshape(size_X, size_Y)

    start = np.where(maze_split == 2)
    end = np.where(maze_split == 3)

    path = astar(maze, start, end)
    print(path)

Sorry if this question has been asked before but I'm stumped at how to get it to work.抱歉,如果之前有人问过这个问题,但我对如何让它发挥作用感到困惑。 Any help would be appreciated!任何帮助,将不胜感激!

import numpy as np

x = np.array([6, 4, 0, 0, 1, 0, 0, 0, 2, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0])

print(x[2:].reshape(x[[1,0]]))

[[0 0 1 0 0 0]
 [2 0 1 0 1 1]
 [0 0 1 0 0 0]
 [0 0 0 0 3 0]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM