如何编写Python程序实现数据过滤与字段补全(禁用字典/列表)
Python数据处理问题修复方案
问题需求
需编写Python程序处理8行名为computers的输入数据,要求如下:
- 将数据分为两类:长度为2的记录、长度为3的记录
- 若长度为2的记录的品牌(第一个字段)与长度为3的记录的品牌一致,将长度为3的记录的第三个字段(计数)补全到对应长度为2的记录中
- 最终输出所有含3个字段的记录,禁止使用字典或列表存储数据
现有程序存在两个问题:丢失第一条记录(仅输出7条),补全逻辑不符合预期。
输入数据
'dell' | {'year': 2011, 'mem': 12} 'dell' | {'year': 2006, 'mem': 12} | 2 'hp' | {'year': 2018, 'mem': 4} | 1 'asus' | {'year': 2016, 'mem': 11} 'asus' | {'year': 2010, 'mem': 11} 'asus' | {'year': 2021, 'mem': 11} | 3 'lenovo' | {'year': 1998, 'mem': 3} | 1 'mac' | {'year': 2019, 'mem': 3} | 1
预期输出
'dell' , {'year': 2011, 'mem': 12} , 2 'dell' , {'year': 2006, 'mem': 12} , 2 'hp' , {'year': 2018, 'mem': 4} , 1 'asus' , {'year': 2016, 'mem': 11} , 3 'asus' , {'year': 2010, 'mem': 11} , 3 'asus' , {'year': 2021, 'mem': 11} , 3 'lenovo' , {'year': 1998, 'mem': 3} , 1 'mac' , {'year': 2019, 'mem': 3} , 1
修复后的代码
# 初始化各品牌计数值变量,规避字典/列表使用限制 dell_count = None hp_count = None asus_count = None lenovo_count = None mac_count = None # 第一次遍历:提取各品牌的计数值 # 若computers是文件对象,需先执行computers.seek(0)重置指针以支持二次遍历 for line in computers: line = line.strip() if not line: continue parts = [p.strip() for p in line.split('|')] if len(parts) == 3: brand = parts[0] count = parts[2] if brand == "'dell'": dell_count = count elif brand == "'hp'": hp_count = count elif brand == "'asus'": asus_count = count elif brand == "'lenovo'": lenovo_count = count elif brand == "'mac'": mac_count = count # 第二次遍历:处理每条记录并输出 for line in computers: line = line.strip() if not line: continue parts = [p.strip() for p in line.split('|')] brand = parts[0] if len(parts) == 2: # 根据品牌匹配对应计数值 if brand == "'dell'": count = dell_count elif brand == "'hp'": count = hp_count elif brand == "'asus'": count = asus_count elif brand == "'lenovo'": count = lenovo_count elif brand == "'mac'": count = mac_count print(f"{parts[0]} , {parts[1]} , {count} ") else: # 长度为3的记录直接转换分隔符输出 print(f"{parts[0]} , {parts[1]} , {parts[2]}")
代码说明
- 两次遍历策略:第一次遍历仅提取各品牌的计数值,用独立变量存储以满足禁用字典/列表的要求;第二次遍历处理每条记录,补全长度为2的记录的计数字段。
- 避免数据丢失:若
computers是文件对象,需在第二次遍历前调用seek(0)重置读取指针,确保能遍历所有行。 - 精准补全逻辑:通过严格的品牌匹配,确保同品牌的长度为2的记录使用对应品牌的计数值,完全符合预期输出要求。
内容的提问来源于stack exchange,提问作者nkah
相关产品推荐
相关产品推荐

