根据 Python 中的一组索引将列表拆分为多个部分 [英] Split a list into parts based on a set of indexes in Python
本文介绍了根据 Python 中的一组索引将列表拆分为多个部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据任意数量的索引将列表拆分为多个部分的最佳方法是什么?例如.给出下面的代码
What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below
indexes = [5, 12, 17]
list = range(20)
返回这样的东西
part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
如果没有索引,它应该返回整个列表.
If there are no indexes it should return the entire list.
推荐答案
这是我能想到的最简单、最pythonic的解决方案:
This is the simplest and most pythonic solution I can think of:
def partition(alist, indices):
return [alist[i:j] for i, j in zip([0]+indices, indices+[None])]
如果输入非常大,那么迭代器解决方案应该更方便:
if the inputs are very large, then the iterators solution should be more convenient:
from itertools import izip, chain
def partition(alist, indices):
pairs = izip(chain([0], indices), chain(indices, [None]))
return (alist[i:j] for i, j in pairs)
当然,非常非常懒惰的解决方案(如果您不介意使用数组而不是列表,但无论如何您始终可以将它们恢复为列表):
and of course, the very, very lazy guy solution (if you don't mind to get arrays instead of lists, but anyway you can always revert them to lists):
import numpy
partition = numpy.split
这篇关于根据 Python 中的一组索引将列表拆分为多个部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文