在子列表中按元素数量拆分列表 [英] split list in sub lists by number of elements

查看:72
本文介绍了在子列表中按元素数量拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,如果我有元素列表

In python, if I have the list of elements

l = ['a', 'b', 'c', 'd', 'e', 'f']

和数字列表

n = [2, 1, 3]

如何用n中的数字拆分列表l?

How I can split the list l by the numbers in n ?

并获取此列表列表

[['a', 'b'], ['c'], ['d', 'e', 'f']]

推荐答案

您可以使用islice:

>>> from itertools import islice
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> n = [2, 1, 3]
>>> it = iter(l)
>>> out = [list(islice(it, size)) for size in n]
>>> out
[['a', 'b'], ['c'], ['d', 'e', 'f']]

这篇关于在子列表中按元素数量拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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