Reputation: 4543
I have two lists, one is of a known length and the other is a random length:
MyList1 = [[1, 2, 3], [4, 5],[5, 6, 7, 8]].
MyList2 = [1, 2, 3, 4 ,5 ,6 ]
I need to print the second one in the following way, where 3 lines is for the number of objects in the first list:
[1, 2, 3]
[4, 5]
[6]
The problem is that I don't know the exact length of this list and the sizes of the lines may not be equal.
I got stuck on doing it with for loop
, but it doesn't seem to work.
Upvotes: 0
Views: 898
Reputation: 10961
Based on your last comment, I think the following will work for you:
>>> l1
[[1, 2, 3], [4, 5], [5, 6, 7, 8]]
>>> l2
[1, 2, 3, 4, 5, 6]
>>> i,s=0,0
>>> while s < len(l2):
print l2[s:s+len(l1[i])]
s += len(l1[i])
i += 1
[1, 2, 3]
[4, 5]
[6]
Upvotes: 0
Reputation: 21506
You can try generator function like this,
my_list1 = [1, 2, 3, 4 ,5 ,6 ]
my_list2 = [1, 2, 3]
def make_list(lst1, lst2):
item_count = len(lst1) / len(lst2)
for ix in range(0, len(lst1), item_count):
yield lst1[ix:ix + item_count]
print list(make_list(my_list1, my_list2))
Upvotes: 0
Reputation: 476
If you're curious how to use a for
loop:
step_size = int(len(list2)/len(list1))
for i in range(0, len(list1) - 1):
start = i * step_size
end = start + step_size
print(list2[start:end])
print(list2[len(list1)*step_size - step_size:])
The print
after the loop prints the last chunk, which might be a different size than the others.
Upvotes: 0
Reputation: 184365
A while
loop will do the trick better.
list1 = [1, 2, 3]
list2 = [1, 2, 3, 4, 5 ,6 ]
start = 0
while start < len(list2):
print list2[start:start+len(list1)]
start += len(list1)
Upvotes: 1