根据Python中的一组索引将列表拆分为多个部分 [英] Split a list into parts based on a set of indexes in Python

查看:538
本文介绍了根据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屋!

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