栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在元组列表Python列表中查找重复项

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在元组列表Python列表中查找重复项

更新 :重新阅读您的问题后,您似乎正在尝试创建对等类,而不是收集键的值。如果

[[(1, 2), (3, 4), (2, 3)]]

应该成为

[(1, 2, 3, 4)]

,那么您将需要将输入解释为图形并应用连接的组件算法。您可以将数据结构转换为邻接列表表示形式,并通过广度优先或深度优先搜索遍历它,或者遍历列表并构建不相交的集合。无论哪种情况,您的代码都会突然涉及很多与图形相关的复杂性,并且很难根据输入的顺序提供任何输出顺序保证。这是一种基于广度优先搜索的算法:

import collections# build an adjacency list representation of your inputgraph = collections.defaultdict(set)for l in ListA:    for first, second in l:        graph[first].add(second)        graph[second].add(first)# breadth-first search the graph to produce the outputoutput = []marked = set() # a set of all nodes whose connected component is knownfor node in graph:    if node not in marked:        # this node is not in any previously seen connected component        # run a breadth-first search to determine its connected component        frontier = set([node])        connected_component = []        while frontier: marked |= frontier connected_component.extend(frontier) # find all unmarked nodes directly connected to frontier nodes # they will form the new frontier new_frontier = set() for node in frontier:     new_frontier |= graph[node] - marked frontier = new_frontier        output.append(tuple(connected_component))

但是,不要只是在不理解的情况下复制它。了解它在做什么,或者编写自己的实现。您可能需要能够维持这一点。(我会使用伪代码,但是Python实际上已经和伪代码一样简单。)

如果我对您的问题的原始解释是正确的,并且您的输入是要汇总的键值对的集合,那么这是我的原始答案:

原始答案

import collectionsclusterer = collections.defaultdict(list)for l in ListA:    for k, v in l:        clusterer[k].append(v)output = clusterer.values()

defaultdict(list)
是一个
dict
,它会自动
list
为所有尚不存在的键创建一个作为值。循环遍历所有元组,收集与同一键匹配的所有值,然后从defaultdict创建一个(key,value_list)对的列表。

(此代码的输出并不完全符合您指定的格式,但我认为此格式更有用。如果要更改格式,那应该很简单。)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646038.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号