python about linking sublist with same number together

2024/10/5 16:09:31

I need to group sublists with the same elements together For example:

list1 =[[1, 0], [2, 1], [30, 32]]

would link [1, 0] and [2, 1] together since they both contain 1 and those two would combine into [0, 1, 2]

So after linking, the new list should be like:

new_list1 = [[1, 0, 2], [30, 32]]

IE: there shouldn't be same number inside a sub-list and order is not important.

A longer example:

list2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]

after linking, it would be

new_list2 = [[2, 3, 4], [6, 5, 7, 8], [13, 14], [30, 32]]

So how can this be done in a general way?

Answer

To group the sublists in a general way you can:

Code:

def linking_sublists(lists):index = {}sets = []for l in lists:found = Nonefor i in l:if i in index:# this list has an element we have already seenif found:# combine two setsto_remove = index[i]if found != to_remove:for j in index[i]:found.add(j)index[j] = foundto_remove.clear()else:found = index[i]if found is not None:s = foundfor i in l:s.add(i)else:s = set(l)sets.append(s)for i in l:index[i] = sreturn [list(sorted(s)) for s in sets if s]

How:

This function uses sets and an index dict to group any list with matching elements into sets and track which elements are already in a set.

Test Code:

list_2 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [13, 14], [30, 32]]
print(linking_sublists(list_2))list_3 = [[2, 3], [4, 3], [6, 5], [7, 6], [7, 8], [30, 32], [4, 5], [3, 4]]
print(linking_sublists(list_3))

Results:

[[2, 3, 4], [5, 6, 7, 8], [13, 14], [30, 32]]
[[2, 3, 4, 5, 6, 7, 8], [30, 32]]
https://en.xdnf.cn/q/119991.html

Related Q&A

what to fix to solve the TypeError: an integer is required (got type str) [duplicate]

This question already has answers here:How can I read inputs as numbers?(10 answers)Closed 6 years ago.I have a problem with the choice of calculation years. python flux2nc.py ../data/output/fluxes/ …

Multiprocessing in python/beautifulsoup issues

Hi guys im fairly new in python. what im trying to do is to move my old code into multiprocessing however im facing some errors that i hope anyone could help me out. My code is used to check a few thou…

Fastest possible generation of permutation with defined element values in Python

Trying to generate permutations, could be used with generator or produced List of Lists (but maybe I need a lot of memory?) Looked on the Internet and SO, but couldnt find a version where I define the…

Obtain coordinates of a Polygon / Multi-polygon around a point in python [duplicate]

This question already has answers here:Draw a polygon around point in scattermapbox using python(2 answers)Closed 2 years ago.I am using plotlys scattermapbox to draw a polygon around a point object. I…

PyCuda Error in Execution

This is my pycuda code for rotation.I have installed the latest cuda drivers and I use a nvidia gpu with cuda support.I have also installed the cuda toolkit and pycuda drivers.Still I get this strange …

Python code to Download Specific JSON key value data through REST API calls

I am trying to write a code in python which download only specific key value in the Calls. So the solution might beDownloading the Raw data and later removing the unwanted through regex or 2)Applying s…

How to measure pairwise distances between two sets of points?

I have two datasets (csv files). Both of them contains latitudes-longitudes of two sets (220 and 4400) of points. Now I want to measure pairwise distances (miles) between these two sets of points (220 …

Interactively Re-color Bars in Matplotlib Bar Chart using Confidence Intervals

Trying to shade the bars in this chart based on the confidence that a selected y-value (represented by the red line) lies within a confidence interval. See recolorBars() method in the class example bel…

Unlock password protected Workbook using VBA or Python

I have a workbook name m.xlsx, but its password protected and Ive forgotten the password. How can I open it or un-protect it?The following code does not work:Unprotect workbook without password I need…

How do I make a variable detect if it is greater than or less than another one?

I am currently learning Python, and I decided to build a small "Guess the Number" type of game. I am using the random feature, and trying to make it so it will detect if the users input is eq…