Python读取数字序列识别数组维度与宽度的实现方法
通用实现逻辑
不需要针对1D、2D数组单独写分支逻辑,一套代码可以兼容任意维度的解析,核心判断规则如下:
- 数组维度由单个元素的字符串长度决定:1位数字是1维数组,2位数字是2维数组,以此类推
- 每个元素从左到右的每一位数字,依次对应从高到低维度的索引值,索引永远从0开始连续递增
- 当检测到最高位(最左侧)索引重新回到0时,说明上一个数组已经遍历结束,此时统计上一个数组每个维度出现过的最大索引值,
最大索引+1就是该维度的宽度 - 整个序列遍历完成后,需要补充处理最后一段未输出的数组
可直接运行的代码
def parse_array_sequence(sequence): if not sequence: return [] # 自动识别数组维度 dimension = len(sequence[0]) result = [] # 记录当前数组各维度的最大索引值 current_dim_max = [0] * dimension for item in sequence: # 拆分当前元素为各维度的整数索引 indices = [int(char) for char in item] # 最高位索引归0且不是序列开头,说明上一个数组结束 if indices[0] == 0 and current_dim_max[0] != 0: width_part = "".join([f"[{max_idx + 1}]" for max_idx in current_dim_max]) result.append(f"A {dimension}D array with a width of {width_part}") # 重置计数,开始统计新数组 current_dim_max = [0] * dimension # 更新各维度的最大索引 for i in range(dimension): if indices[i] > current_dim_max[i]: current_dim_max[i] = indices[i] # 处理最后一个数组 width_part = "".join([f"[{max_idx + 1}]" for max_idx in current_dim_max]) result.append(f"A {dimension}D array with a width of {width_part}") return result # 1D数组测试 seq_1d = ['0','1','2','0','1','2','3','4'] for output_line in parse_array_sequence(seq_1d): print(output_line) print("="*20) # 2D数组测试 seq_2d = ['00','01','02','03','10','11','12','13','00','01','10','11'] for output_line in parse_array_sequence(seq_2d): print(output_line)
运行结果
A 1D array with a width of [3] A 1D array with a width of [5] ==================== A 2D array with a width of [2][4] A 2D array with a width of [2][2]
和题目给出的示例输出完全一致。后续如果需要支持3维及更高维度的数组,只要输入元素的位数对应维度数即可,不需要修改核心代码逻辑。
内容的提问来源于stack exchange,提问作者Zaruta Tadashi
相关产品推荐
相关产品推荐

