Python3如何按嵌套列表中子列表的首元素去重并保留首个出现项
Python3 按子列表首元素去重实现方法
实现思路
遍历嵌套列表时用集合记录已经出现过的首元素值,仅将首元素未出现过的子列表加入结果集,保证仅保留第一个出现的同首元素子列表,时间复杂度为O(n),同时保留原列表的元素顺序。
完整实现代码
def deduplicate_by_first_element(input_list): seen = set() output = [] for sub_lst in input_list: # 兼容空子列表的边界场景,不需要可删除该判断 if not sub_lst: continue first_key = sub_lst[0] if first_key not in seen: seen.add(first_key) output.append(sub_lst) return output
效果验证
用给出的三个输入测试,结果完全符合预期:
# 测试输入 input1 = [ ['nom', 'N', 'eye'], ['nom', 'N', 'face'], ['acc', 'E', 'computer'], ['dat', 'C', 'screen'] ] input2 = [ ['nom', 'O', 'heart'], ['acc', 'O', 'root'], ['acc', 'C', 'life'], ['dat', 'E', 'evidence'] ] input3 = [ ['nom', 'O', 'author'], ['acc', 'O', 'tear'], ] # 输出结果 print(deduplicate_by_first_element(input1)) # [['nom', 'N', 'eye'], ['acc', 'E', 'computer'], ['dat', 'C', 'screen']] print(deduplicate_by_first_element(input2)) # [['nom', 'O', 'heart'], ['acc', 'O', 'root'], ['dat', 'E', 'evidence']] print(deduplicate_by_first_element(input3)) # [['nom', 'O', 'author'], ['acc', 'O', 'tear']]
内容的提问来源于stack exchange,提问作者Carlos Luis Rivera
相关产品推荐
相关产品推荐

