I have two types of lists. One is always smaller than the other.
I want to split the longer list in sublists based on the length of the smaller list. E.g.,
a = [1,2,3,4]
b = [1,2,3,4,5,6,7,8,9,10]
desired output =
sub_list 1 = [1,2,3,4] , sub_list 2 = [5,6,7,8], sub_list 3 = [7,8,9,10]
Since only two unique items are left in the last list and to preserve the structure of the last sub_list, repeat the elements just before the last unique elements till it gets to the same length as that of the smaller list.
I tried doing this:
def create_sublists(a, b):
smaller_list_length = len(a)
num_sublists = len(b) // smaller_list_length
b_sublists = []
for i in range(num_sublists):
start_index = i * smaller_list_length
end_index = start_index + smaller_list_length
b_sublist = b[start_index:end_index]
if len(b_sublist) < smaller_list_length:
preceding_numbers = b[start_index - smaller_list_length:start_index]
num_missing = smaller_list_length - len(b_sublist)
b_sublist = preceding_numbers[-num_missing:] + b_sublist
b_sublists.append(b_sublist)
return b_sublists
But this is not always giving the desired result, and it also doesn’t check for which list is smaller automatically.
How can I do it?
Just check the list lengths beforehand. Something like this.
-chatgpt