在 python 中,如果我有元素列表
l = ['a', 'b', 'c', 'd', 'e', 'f']
和一个数字列表
n = [2, 1, 3]
我如何拆分列表l
通过中的数字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']]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)