Python Forum
List of lists - merge sublists with common elements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of lists - merge sublists with common elements
Assume I have list1 as follows:

list1 = [['a','b'],['c','d'],['b','e'],['f','g'],['a','h'],['i','c']]
I want to merge the sublists that have common elements, so based on the above example the resulting list will be

list2 = [['a','b','e','h'],['c','d','i'],['f','g']]
I could do things like parse each element separately and do comparisons all over etc. but the input list can be pretty long (maybe many hundreds or even millions of elements overall) Is there an efficient way to do this in python?
This is a version of the problem of finding the connected components of a graph. One approach would be to use a library that already has a function to do that, such as networkx.
>>> import networkx as nx
>>> g = nx.Graph()
>>> ipath = [['a','b'],['c','d'],['b','e'],['f','g'],['a','h'],['i','c']]
>>> for p in ipath:
...     g.add_edges_from(zip(p, p[1:]))
>>> for c in nx.connected_components(g):
...     print(c)
{'e', 'h', 'a', 'b'}
{'i', 'c', 'd'}
{'g', 'f'}

Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 804 May-17-2022, 11:38 AM
Last Post: Larz60+
  How to efficiently average same entries of lists in a list xquad 5 873 Dec-17-2021, 04:44 PM
Last Post: xquad
  sorting a list of lists by an element leapcfm 3 902 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  Why am I getting list elements < 0 ? Mark17 8 1,660 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 1,075 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Extracting Elements From A Website List knight2000 2 1,026 Jul-20-2021, 10:38 AM
Last Post: knight2000
  Make Groups with the List Elements quest 2 1,176 Jul-11-2021, 09:58 AM
Last Post: perfringo
  behavior list of lists roym 5 1,035 Jul-04-2021, 04:43 PM
Last Post: roym
  I cannot delete and the elements from the list quest 4 1,779 May-11-2021, 12:01 PM
Last Post: perfringo
  Take first Elements of sublists quest 2 1,205 Apr-26-2021, 11:32 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020