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.
CodePudding user response:
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.
CodePudding user response:
This is written in Python3. Hope this helps!
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"]
def reformat_list(source, target):
tmp = source
source = []
for letter in target:
if letter in tmp:
source = [letter]
else:
source = ['0']
return source
lst1 = reformat_list(lst1, main_lst1)
lst2 = reformat_list(lst2, main_lst1)
lst3 = reformat_list(lst3, main_lst1)
print(lst1)
print(lst2)
print(lst3)