如何合并二维列表中连续相同ID对应的错误字符串
问题描述
给定一个二维列表inputList,其中每个元素由ID和错误信息组成。需要将连续出现的相同ID对应的所有错误信息进行拼接,最终得到类似outputList的结果。
示例:
inputList = [["12","hello"],["12","hello"],["12","hello"],["13","hi"],["13","hi"],["12","hello"]] outputList = ["hellohellohello","hihi","hello"]
解决方案
以下是用Python实现的代码,通过遍历跟踪当前ID和拼接字符串来完成需求:
inputList = [["12","hello"],["12","hello"],["12","hello"],["13","hi"],["13","hi"],["12","hello"]] outputList = [] if not inputList: print(outputList) else: current_id, current_msg = inputList[0] for id_, msg in inputList[1:]: if id_ == current_id: current_msg += msg else: outputList.append(current_msg) current_id, current_msg = id_, msg # 添加最后一组的拼接结果 outputList.append(current_msg) print(outputList) # 输出: ['hellohellohello', 'hihi', 'hello']
逻辑说明
- 先处理输入为空的边界情况,直接返回空列表
- 初始化当前跟踪的ID和拼接字符串为列表第一个元素的对应值
- 从第二个元素开始遍历列表:
- 若当前元素ID与跟踪的ID一致,就把错误信息追加到拼接字符串中
- 若ID不一致,就把当前拼接好的字符串存入结果列表,同时更新跟踪的ID和拼接字符串为当前元素的值
- 遍历结束后,必须把最后一组的拼接结果加入结果列表,避免遗漏
内容的提问来源于stack exchange,提问作者Raman
相关产品推荐
相关产品推荐

