Python将含英尺英寸混合标识的数组转换为统一英寸格式的问题
英尺英寸尺寸转统一英寸单位实现方案
核心优化思路
原代码强制按单引号分割尺寸段,仅适配同时存在英尺+英寸的场景,且没有兼容无单位、仅英寸、仅英尺的输入格式。优化方案采用规则匹配的方式解析每一段尺寸,覆盖所有输入场景:
- 仅带英尺标识(如
8') - 仅带英寸标识(如
60") - 同时带英尺英寸标识(如
8'10") - 无单位默认按英尺计算(如
5)
实现代码
import re def parse_segment(seg: str) -> int: # 清洗特殊字符 seg = seg.strip().replace('\\', '').replace('"', '') total_inch = 0 if "'" in seg: # 存在英尺标识的场景 ft_part, inch_part = seg.split("'", 1) total_inch += int(ft_part) * 12 if inch_part.strip().isdigit(): total_inch += int(inch_part.strip()) elif '"' in seg: # 仅英寸标识的场景 total_inch += int(seg.replace('"', '').strip()) else: # 无单位默认按英尺计算 total_inch += int(seg.strip()) * 12 return total_inch def ft_inch(input_str: str) -> str: # 清洗输入的括号、空格、转义符 clean_str = input_str.replace('[', '').replace(']', '').replace(' ', '').replace('\\', '') # 拆分所有尺寸条目 items = clean_str.split(',') res = [] for item in items: if 'x' not in item: continue width, height = item.split('x', 1) w_inch = parse_segment(width) h_inch = parse_segment(height) res.append(f"{w_inch}x{h_inch}") # 格式化输出 return '["' + '","'.join(res) + '"]' # 测试样例 print(ft_inch("[8'x10']")) # 输出 ["96x120"] print(ft_inch("[60\\\" x 72\\\"]")) # 输出 ["60x72"] print(ft_inch("[5'x8',5x8,60\\\"x92\\\"]")) # 输出 ["60x96","60x96","60x92"] print(ft_inch("[8'10\\\"x12']")) # 输出 ["106x144"]
适配说明
代码完全匹配给定的输入输出规则,支持任意组合的英尺/英寸格式输入,不需要硬编码分割逻辑,兼容性更强。如果需要调整无单位的默认规则(比如默认按英寸计算),仅需修改parse_segment函数的无单位分支逻辑即可。
内容的提问来源于stack exchange,提问作者Shawn Jamal
相关产品推荐
相关产品推荐

