Tatu Bogdan
Tatu Bogdan

Reputation: 596

Merge function will only work for ordered list

I have this 2 lists as input:

list1 = [['A', 14, 'I', 10, 20], ['B', 15, 'S', 30, 40], ['C', 16, 'F', 50, 60]]
list2 = [['A', 14, 'Y', 0, 200], ['B', 15, 'M', 0, 400], ['C', 17, 'G', 0, 600]]

and my desired output will be this:

finalList = [['A', 14, 'Y', 10, 200], ['B', 15, 'M', 30, 400], ['C', 16, 'F', 50, 60],['C', 17, 'G', 0, 600]]

Using this function:

def custom_merge(list1, list2):
    finalList = []
    for sub1, sub2 in zip(list1, list2):
        if sub1[1]==sub2[1]:
            out = sub1.copy()
            out[2] = sub2[2]
            out[4] = sub2[4]
            finalList.append(out)
        else:
            finalList.append(sub1)
            finalList.append(sub2)
    return finalList

I will get indeed my desired output, but what if I switch positions (list2[1] and list2[2]) and my list2:

list2 = [['A', 14, 'Y', 0, 200], ['C', 17, 'G', 0, 600], ['B', 15, 'M', 0, 400]]

Then the output will be this:

[['A', 14, 'Y', 10, 200], ['B', 15, 'S', 30, 40], ['C', 17, 'G', 0, 600], ['C', 16, 'F', 50, 60], ['B', 15, 'M', 0, 400]]

(notice the extra ['B', 15, 'M', 0, 400])

What I have to modify in my function in order to get my first desired output if my lists have a different order in my list of lists!? I use python 3. Thank you!

LATER EDIT:

Merge rules: When list1[listindex][1] == list2[listindex][1] (ex: when 14==14), replace in list1 -> list2[2] and list2[4] (ex: 'Y' and 200) and if not just add the unmatched list from list2 to list1 as it is (like in my desired output) and also keep the ones that are in list1 that aren't matched(ex: ['C', 16, 'F', 50, 60])

To be noted that list1 and list2 can have different len (list1 can have more lists than list2 or vice versa)

EDIT.2 I found this:

def combine(list1,list2):
    combined_list = list1 + list2
    final_dict = {tuple(i[:2]):tuple(i[2:]) for i in combined_list}
    merged_list = [list(k) + list (final_dict[k]) for k in final_dict]
    return merged_list 

^^ That could work, still testing!

Upvotes: 1

Views: 57

Answers (1)

James
James

Reputation: 36756

You can sort the lists by the first element in the sublists before merging them.

def custom_merge(list1, list2):
    finalList = []
    for sub1, sub2 in zip(sorted(list1), sorted(list2)):
        if sub1[1]==sub2[1]:
            out = sub1.copy()
            out[2] = sub2[2]
            out[4] = sub2[4]
            finalList.append(out)
        else:
            finalList.append(sub1)
            finalList.append(sub2)
    return finalList

tests:

list1 = [['A', 14, 'I', 10, 20], ['B', 15, 'S', 30, 40], ['C', 16, 'F', 50, 60]]
list2 = [['A', 14, 'Y', 0, 200], ['C', 17, 'G', 0, 600], ['B', 15, 'M', 0, 400]]
custom_merge(list1, list2)
# returns:
[['A', 14, 'Y', 10, 200],
 ['B', 15, 'M', 30, 400],
 ['C', 16, 'F', 50, 60],
 ['C', 17, 'G', 0, 600]]

Upvotes: 1

Related Questions