简体   繁体   中英

How to print different parts of a list on new line in Python?

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.

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)

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.

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))

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM