如何从字典列表中过滤重复双向连接,仅保留唯一条目
解决双向连接去重问题
问题描述
给定字典列表:
x = [ {'local': 'a', 'local_int' : 'b', 'remote': 'c', 'remote_int': 'd'}, {'local': 'c', 'local_int' : 'd', 'remote': 'a', 'remote_int': 'b'}, {'local': 'g', 'local_int' : 'h', 'remote': 'e', 'remote_int': 'f'}, {'local': 'e', 'local_int' : 'f', 'remote': 'g', 'remote_int': 'h'} ]
其中x[0]与x[1]、x[2]与x[3]属于同一双向连接,需要过滤重复项,仅保留唯一的连接条目。
解决方案
核心思路是为每个连接生成不区分方向的唯一标识,用集合记录已处理的标识,遍历列表时只保留首次出现的连接。
代码实现
x = [ {'local': 'a', 'local_int' : 'b', 'remote': 'c', 'remote_int': 'd'}, {'local': 'c', 'local_int' : 'd', 'remote': 'a', 'remote_int': 'b'}, {'local': 'g', 'local_int' : 'h', 'remote': 'e', 'remote_int': 'f'}, {'local': 'e', 'local_int' : 'f', 'remote': 'g', 'remote_int': 'h'} ] seen = set() unique_connections = [] for conn in x: # 提取本地端和远程端的配对信息 local_pair = (conn['local'], conn['local_int']) remote_pair = (conn['remote'], conn['remote_int']) # 对配对信息排序,让双向连接生成相同的唯一键 connection_key = tuple(sorted([local_pair, remote_pair])) if connection_key not in seen: seen.add(connection_key) unique_connections.append(conn) # 输出结果 for conn in unique_connections: print(conn)
代码说明
- 生成唯一标识:将每个连接的本地端(
local+local_int)和远程端(remote+remote_int)打包成元组,再对这两个元组排序。这样双向连接会生成完全一致的connection_key,比如ab<->cd和cd<->ab的键都是(('a','b'), ('c','d'))。 - 去重逻辑:用集合
seen存储已处理过的connection_key,遍历原列表时,仅当当前连接的键未被记录时,才将其加入结果列表。
运行结果
{'local': 'a', 'local_int': 'b', 'remote': 'c', 'remote_int': 'd'} {'local': 'g', 'local_int': 'h', 'remote': 'e', 'remote_int': 'f'}
内容的提问来源于stack exchange,提问作者kryton007
相关产品推荐
相关产品推荐

