如何用for循环读取含数值的TXT文件并转换为N×N矩阵
问题描述
我正在计算城市间的距离,文本文件存储了所有待访问城市间的距离。若有N个城市,文件中则是一个N×N的浮点数数组,其中元素(i,j)代表城市i到城市j的距离。我已创建好全0的N×N矩阵,且读取了文件第一行,如何用for循环将文件内容转换为目标N×N矩阵?
示例文件内容
small_distances.txt的内容如下:
0.0 2.0 2.23606797749979 4.47213595499958 5.385164807134504 2.0 0.0 2.23606797749979 4.0 3.605551275463989 2.23606797749979 2.23606797749979 0.0 2.23606797749979 4.0 4.47213595499958 4.0 2.23606797749979 0.0 3.605551275463989 5.385164807134504 3.605551275463989 4.0 3.605551275463989 0.0
现有代码
def create_2_list(rows,columns): the_2d_list = [] for i in range(rows): current_row = [] for j in range(columns): current_row.append(0) the_2d_list.append(current_row) return the_2d_list def print_2d_list(the_list): for i in range(len(the_list)): for j in range(len(the_list[i])): print(the_list[i][j], end=' ') print() def read_line_in_txt(file): file = open(filename,'r') line = file.readline() t = line.split() return t filename = 'small_distances.txt' the_file = open(filename,'r') the_data = the_file.readlines() the_file.close() n_cities = len(the_data) distances = create_2_list(n_cities,n_cities) print_2d_list(distances) print('---------------------------') line = read_line_in_txt(the_data) print(line) print('---------------------------')
预期输出
0.0 2.0 2.23606797749979 4.47213595499958 5.385164807134504 2.0 0.0 2.23606797749979 4.0 3.605551275463989 2.23606797749979 2.23606797749979 0.0 2.23606797749979 4.0 4.47213595499958 4.0 2.23606797749979 0.0 3.605551275463989 5.385164807134504 3.605551275463989 4.0 3.605551275463989 0.0
文本行拆分示例
通过拆分文本行可得到城市距离列表:
# 文本文件第一行 t = '0.0 2.0 2.23606797749979 4.47213595499958 5.385164807134504' t.split() # 输出结果: # ['0.0', '2.0', '2.23606797749979', '4.47213595499958', '5.385164807134504'] # 对应城市1到城市2、3、4、5的距离 len(t.split()) # 输出结果:5 # 利用这个信息可以通过嵌套for循环构建距离矩阵
解决方案
要将文件内容填充到全0矩阵中,只需遍历已读取的每一行数据,拆分后转换为浮点数,再通过for循环逐个赋值到矩阵对应位置即可。同时需要修正现有代码中read_line_in_txt函数的错误(该函数参数未被使用,且重复打开文件,实际无需单独定义此函数)。修改后的完整代码如下:
def create_2_list(rows, columns): the_2d_list = [] for i in range(rows): current_row = [] for j in range(columns): current_row.append(0) the_2d_list.append(current_row) return the_2d_list def print_2d_list(the_list): for i in range(len(the_list)): for j in range(len(the_list[i])): print(the_list[i][j], end=' ') print() filename = 'small_distances.txt' the_file = open(filename, 'r') the_data = the_file.readlines() the_file.close() n_cities = len(the_data) distances = create_2_list(n_cities, n_cities) # 用for循环填充矩阵 for i in range(n_cities): # 去除行尾换行符并拆分字符串 row_data = the_data[i].strip().split() for j in range(n_cities): # 将字符串转换为浮点数后赋值 distances[i][j] = float(row_data[j]) # 打印结果 print_2d_list(distances)
代码说明
- 外层
for循环遍历每一行数据,对应矩阵的行索引i - 对每一行先去除换行符,再用
split()拆分得到距离字符串列表 - 内层
for循环遍历每个距离值,对应矩阵的列索引j - 将字符串转换为浮点数,赋值到
distances[i][j]位置
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

