python list分成多个_根据Python中的一组索引将列表分成多个部分

本文介绍了一种使用Python将列表按指定索引进行分割的方法,并提供了两种实现方案:一种为简洁的列表推导方式,另一种利用了迭代器的方式适用于大型数据集。此外还提供了一个使用NumPy的懒惰解决方案。

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)

return something like this

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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值