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
#1
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?
Reply
#2
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'}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Merge list Simso 2 819 Oct-03-2024, 01:44 PM
Last Post: snippsat
  unable to remove all elements from list based on a condition sg_python 3 1,725 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 1,673 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  List all possibilities of a nested-list by flattened lists sparkt 1 1,805 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Checking if a string contains all or any elements of a list k1llcod3 1 5,023 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  user input values into list of lists tauros73 3 2,009 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 2,008 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 3,139 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  How to change the datatype of list elements? mHosseinDS86 9 3,733 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 8,286 May-17-2022, 11:38 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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