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’ ] ]
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.