如何将python列表划分为不等长的子列表? [英] How to divide python list into sublists of unequal length?

查看:484
本文介绍了如何将python列表划分为不等长的子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将逗号分隔的元素列表分成长度不等的块.我如何分割它?

I am trying to divide a list of elements which are comma separated into chunks of unequal length. How can I divide it?

list1 = [1, 2, 1]
list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]

list1包含一些元素,这些元素是我希望将list2分成的块的大小.

list1 contains the elements which are the sizes of chunks which I wish to divide the list2 in.

推荐答案

另一个解决方案

list1 = [1,2,1]
list2 = ["1.1.1.1","1.1.1.2","1.1.1.3","1.1.1.4"]

chunks = []
count = 0
for size in list1:
    chunks.append([list2[i+count] for i in range(size)])
    count += size
print(chunks)

# [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]

这篇关于如何将python列表划分为不等长的子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆