简体   繁体   English

在Python中从文件读取二维数组

[英]Reading 2d array from file in Python

The following code fills a 2d array (grid) with random numbers(0 or 1): 以下代码使用随机数(0或1)填充2d数组(网格):

def create_initial_grid(rows, cols):

grid = []
for row in range(rows):
    grid_rows = []
    for col in range(cols):

        if random.randint(0, 7) == 0:
            grid_rows += [1]
        else:
            grid_rows += [0]

    grid += [grid_rows]
return grid

I want to fill the grid from a text file that looks like this: 我想从看起来像这样的文本文件中填充网格:

7
0,0,0,0,0,0,0
0,0,1,0,1,0,0
0,0,1,1,1,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0

You can read the file, with: 您可以通过以下方式读取文件:

with open('myfile.txt') as f:
    next(f)  # skip the first line
    data = [list(map(int, line.strip().split(','))) for line in f]

Here next(..) will move the cursor to the next line, since the first here contains a 7 . next(..)将光标移至下一行,因为此处的第一行包含7

If there is data after the lines, we might want to prevent reading that, and use: 如果这些行后面有数据,我们可能要防止读取该数据,并使用:

from itertools import islice

with open('myfile.txt') as f:
    n = int(next(f))  # skip the first line
    data = [list(map(int, line.strip().split(','))) for line in islice(f, n)]

For both file fragments here, the result is: 对于此处的两个文件片段,结果为:

>>> data
[[0, 0, 0, 0, 0, 0, 0],
 [0, 0, 1, 0, 1, 0, 0],
 [0, 0, 1, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0]]
filesname = "t.txt"

with open(filesname) as f:
    lines = f.read().split()

n = lines[0]
data_lines = lines[1:]

data = [map(int, row.split(",")) for row in data_lines]

print(data)

Hope this helps! 希望这可以帮助!

Other option is to use numpy.loadtxt to read .txt (since you are use the array and matrix format): 另一个选择是使用numpy.loadtxt读取.txt (因为您使用的是arraymatrix格式):

data = np.loadtxt("text.txt", delimiter=",",dtype=int , skiprows=1) 
print(data)

Out: 出:

 [[0 0 0 0 0 0 0] [0 0 1 0 1 0 0] [0 0 1 1 1 0 0] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0] [0 0 0 0 0 0 0]] 

Note: 注意:

skiprows=1 # parameter for skipping the first line when reading from the file. skiprows=1 #用于从文件读取时跳过第一行的参数。

dtype=int parameter for reading in the int format (default is float ) dtype=int参数,以int格式读取(默认为float

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

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