Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combining lists that repeat values

I have this List:

result = [['A', 100], ['A', 200], ['A', 300], ['A', 100, 'WERKS'], [A, 200, 'MATNR'], [A, 300, 'RESNR']]

I’ve been trying to remove lists that are duplicates of others. So, [A, 100] is a small duplicate of [A, 100, WERKS]. Therefore [A,100] would be removed. If the list can be found within another list it will be removed. Is there a way to do this in python?

new list should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result2 = [['A',100, 'WERKS'], ['A', 200, 'MATNR'], [A, 300, 'RESNR']]

>Solution :

You could achieve this using set comparisons and a list comprehension. If any sublist converted to set is a strict subset of another, then don’t keep it.

sets = list(map(set, result))
out = [l for l in result if not any(set(l)<s for s in sets)]

Be aware that the worst complexity is O(n**2)!

output:

[['A', 100, 'WERKS'], ['A', 200, 'MATNR'], ['A', 300, 'RESNR']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading