Python中如何将含数字的文件转为列表并统计4*4矩阵邻接1的数量
解决方案
问题说明
你提到的“上下左右方向邻接”实际对应**八邻域(上下左右+四个对角线)**的统计,因为按你的期望输出反推,只有统计八邻域的1数量才能得到结果。下面是完整的实现步骤:
1. 读取文件并转换矩阵
将文本文件中的制表符分隔内容读取,同时把1映射为True、0映射为False,生成布尔类型的二维矩阵:
# 读取矩阵文件 with open('matrix.txt', 'r') as file: # 定义映射关系 value_map = {'1': True, '0': False} # 逐行处理:分割制表符、转换类型、过滤空内容 bool_matrix = [] for line in file: cleaned_line = line.strip() if not cleaned_line: continue # 按制表符分割元素,转换为布尔值 row = [value_map[item.strip()] for item in cleaned_line.split('\t') if item.strip()] bool_matrix.append(row)
2. 统计八邻域的1数量
遍历矩阵每个元素,检查其8个方向的邻接元素(需确保邻接坐标在矩阵范围内),统计其中True(即原矩阵的1)的数量:
# 定义八邻域的方向偏移(行差, 列差) neighbor_dirs = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] rows = len(bool_matrix) cols = len(bool_matrix[0]) if rows > 0 else 0 count_matrix = [] for i in range(rows): current_row = [] for j in range(cols): neighbor_count = 0 for dx, dy in neighbor_dirs: # 计算邻接元素的坐标 x = i + dx y = j + dy # 检查坐标是否在矩阵边界内 if 0 <= x < rows and 0 <= y < cols: # 如果邻接元素是True(原1),计数+1 if bool_matrix[x][y]: neighbor_count += 1 current_row.append(neighbor_count) count_matrix.append(current_row)
3. 输出结果矩阵
将统计后的矩阵按制表符分隔格式打印,与你的期望输出一致:
# 打印结果 for row in count_matrix: print('\t'.join(map(str, row)))
验证结果
运行上述代码后,输入你提供的原矩阵,输出将与期望完全一致:
1 3 2 2 1 4 5 4 3 4 4 5 1 2 4 2
内容的提问来源于stack exchange,提问作者farbod al
相关产品推荐
相关产品推荐

