简体   繁体   English

如何在Python的新行上打印列表的不同部分?

[英]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: 我需要以以下方式打印第二个,其中第3个行表示第一个列表中的对象数:

[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. 我被困在for loop ,但这似乎行不通。

A while loop will do the trick better. while循环会更好。

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: 如果您好奇如何使用for循环:

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. print循环后打印的最后一块,这可能是不同的大小比其他人。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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