0 votes
1 view
in Python by (12.1k points)

I have a list of records. My point is to check whether anyone sublist shares anything common with other sublists(excluding the principal list object to think about). On the off chance that it shares common, at that point bring together those sublists. 

[[1, '34', '44'], [1, '40', '30', '41'], [1, '41', '40', '42'], [1, '42', '41', '43'], [1, '43', '42', '44'], [1, '44', '34', '43']]

For instance, for this model my last answer should be the like thing:

[[1, '34, '44', '40' '30', '41', '42', '43']]

I can comprehend that I should change the sublists over to sets and afterward utilize association() and intersection() activity. Yet, what I am left with is to how to look at each set/sublist. I can't run a loop over the list and think about every sublist individually as the substance of the list would be changed and this would prompt a mistake. 

What I need to know is there any productive technique to contrast all the sublists(converted with sets) and get a union of them?

1 Answer

0 votes
by (25.2k points)

The itertools module makes short work of this issue: 

>>> from itertools import chain

>>> list(set(chain.from_iterable(d)))

[1, '41', '42', '43', '40', '34', '30', '44']

Another approach to do it is to unload the list into independent arguments for union(): 

>>> list(set().union(*d))

[1, '41', '42', '43', '40', '34', '30', '44']

The last way takes out all copies and doesn't need that the data sources initially be changed over to sets. Likewise, it doesn't need an import.

Interested to learn the concepts of python in detail? Come and join the python course to gain more knowledge in python

Watch this video tutorial on how to become a professional in python

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...