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 similar elements of an Array

I would like to create a function which loops through an array and combines the third element of each if they have the same first two elements, however only ways I could think of have a very high complexity, any recommended algorithm [python preferred, but any pseudo-code or algorithm will do]:

example input -> Delta = [ [0, 0, ‘1’], [0, 1, ‘1’], [1, 2, ‘0’], [1, 2, ‘1’], [2, 2, ‘0’], [2, 2, ‘1’] ]

expected output -> Delta = [ [0, 0, ‘1’ ], [0, 1, ‘1’ ], [1, 2, ‘0, 1’ ], [2, 2, ‘0, 1’ ] ]

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

Thanks for your time

>Solution :

You could sort the lists and then use a loop:

from typing import List, Union


def merge_lists(lists: List[List[Union[int, str]]]) -> List[List[Union[int, str]]]:
    """Merges lists based on first two elements."""
    if not lists:
        return lists
    sorted_lists = sorted(lists)
    result = [sorted_lists[0]]
    for sub_list in sorted_lists[1:]:
        curr_first, curr_second, key = sub_list
        prev_first, prev_second, *keys = result[-1]
        if curr_first == prev_first and curr_second == prev_second and key not in keys:
            result[-1].append(key)
        else:
            result.append(sub_list)
    return [[first, second, ', '.join(keys)] for first, second, *keys in result] 


lists = [[0, 0, '1'], [0, 1, '1'], [1, 2, '0'], [1, 2, '1'], [2, 2, '0'], [2, 2, '1']]
print(f'{lists = }')
print(f'{merge_lists(lists) = }')

Output:

lists = [[0, 0, '1'], [0, 1, '1'], [1, 2, '0'], [1, 2, '1'], [2, 2, '0'], [2, 2, '1']]
merge_lists(lists) = [[0, 0, '1'], [0, 1, '1'], [1, 2, '0, 1'], [2, 2, '0, 1']]

If the first two elements are strings instead of numbers, use something like natsort.

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