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

时间:2018-10-27 18:05:49

标签: python

以下代码用随机数(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

我想从看起来像这样的文本文件中填充网格:

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

3 个答案:

答案 0 :(得分:0)

您可以通过以下方式读取文件:

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

此处next(..)将光标移至下一行,因为此处的第一行包含7

如果这些行之后有数据 ,我们可能要防止读取该数据,并使用:

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)]

对于这两个文件片段,结果都是:

>>> 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]]

答案 1 :(得分: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)

希望这会有所帮助!

答案 2 :(得分:0)

其他选择是使用numpy.loadtxt来读取.txt(因为您使用的是arraymatrix格式):

data = np.loadtxt("text.txt", delimiter=",",dtype=int , skiprows=1) 
print(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]]
     

注意:

     

skiprows=1#参数,用于从中读取时跳过第一行   文件。

     

dtype=int参数,以int格式读取(默认为   float