Python遍历嵌套列表并合并条目:交易数据清洗需求
解决Python数据清理:合并特定子列表的方案
需求说明
处理包含6元素子列表的transaction_list:识别出仅索引1的元素非空、其余均为空字符串的子列表,将其索引1的元素以换行符\n合并到前一个子列表的对应位置,随后删除该子列表,最终得到可转为DataFrame的干净列表。
实现代码
# 初始化存储清理后数据的列表 cleaned_transactions = [] for item in transaction_list: # 判断当前子列表是否为待合并的候选项 # 条件:索引1元素非空(排除纯空白),其余位置全为空字符串 is_merge_target = (item[1].strip() != "") and all(x == "" for x in item[:1] + item[2:]) if is_merge_target and cleaned_transactions: # 合并到前一个子列表的索引1位置 last_item = cleaned_transactions[-1] last_item[1] = f"{last_item[1]}\n{item[1]}" else: # 复制子列表避免修改原数据引用,添加到结果列表 cleaned_transactions.append(item.copy())
关键细节说明
- 候选项判断逻辑:
all(x == "" for x in item[:1] + item[2:])用来检查除索引1外的所有元素是否为空,结合item[1].strip() != ""确保索引1的元素是有效内容而非空白字符 - 避免索引越界:判断
cleaned_transactions不为空才执行合并,防止第一个元素就是候选项时出错 - 数据独立性:使用
item.copy()复制子列表,避免后续修改影响原始transaction_list中的数据
示例验证
假设原始列表为:
transaction_list = [ ["a", "b", "", "", "", ""], ["", "c", "", "", "", ""], # 符合合并条件 ["d", "e", "f", "", "", ""], ["", "g", "", "", "", ""], # 符合合并条件 ["", "", "h", "", "", ""], # 不符合(索引2非空) ]
处理后得到的cleaned_transactions为:
[ ["a", "b\nc", "", "", "", ""], ["d", "e\ng", "f", "", "", ""], ["", "", "h", "", "", ""], ]
内容的提问来源于stack exchange,提问作者clattenburg cake
相关产品推荐
相关产品推荐

