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

Merging list based on values

I have 4 lists of different lengths, simplifying:

main_lst1= ["a", "b", "c", "d", "e", "f", "g"] - with all values

lst1 = ["a", "c", "d", "e", "f"]
lst2 = ["a", "b", "c", "d", "e", "g"]
lst3 = ["c", "d", "e", "f", "g"]

and I need to combine/ merge that lists to get:

lst1 = ["a", 0, "c", "d", "e", "f", 0]
lst2 = ["a", "b", "c", "d", "e", 0, "g"]
lst3 = [0, 0, "c", "d", "e", "f", "g"]

I hope that is enough explanation what I need to get.
Kindly help.

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

>Solution :

I’m going to assume that lst1, lst2, and lst3 are alphabetically sorted and that they would only have the characters from main_lst1.

Something like this should work:

main_lst1 = ["a", "b", "c", "d", "e", "f", "g"]

lst1 = ["a", "c", "d", "e", "f"]
lst2 = ["a", "b", "c", "d", "e", "g"]
lst3 = ["c", "d", "e", "f", "g"]

for cur_lst in (lst1, lst2, lst3):
    cur_i = 0
    while len(cur_lst) != len(main_lst1):
        if cur_lst[cur_i] != main_lst1[cur_i]:
            cur_lst.insert(cur_i, 0)
        cur_i += 1
        if cur_i == len(cur_lst):
            cur_lst.append(0)
            break

    print(cur_lst)

Basically, I loop over the list and insert 0 when I find that the character doesn’t match that of the main list. Of course, if the assumptions I made earlier aren’t correct, then this solution will need more alterations to work.

Edit: Also note that since lists are mutable in python, the above code would alter the original lists.

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