Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two lists in equal amounts

Tags:

python

list

The problem is to merge two lists while keeping the order, and to have the same number of items in the merged list, which can not hold more than 10 (or any number) items, but as many as possible.

This is the most simple example.

l1 = list('1'*10)
l2 = list('2'*10)
lt = l1[:5] + l2[:5]

However, when one list doesn't have 5 items, the new list is filled up with items from the other list.

l1 = list('1'*2)
l2 = list('2'*10)
lt = ['1','1','2','2','2','2','2','2','2','2']

l1 = list('1'*10)
l2 = list('2'*2)
lt = ['1','1','1','1','1','1','1','1','2','2']

The function should take lists with any number of items. This should be simple but isn't.


1 Answers

You want to take which ever is greater: five items from the list or enough items to fill the list to the desired length.

lt = l1[:max(5, 10 - len(l2))] + l2[:max(5, 10 - len(l1))]
like image 112
agf Avatar answered Dec 02 '25 05:12

agf