根据另一个列表的索引将列表拆分为块 [英] Split lists into chunk based of index of another list

查看:154
本文介绍了根据另一个列表的索引将列表拆分为块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用另一个列表的值作为要拆分的范围将一个列表拆分为多个块.

I want to split a list into chunks using values of of another list as the range to split.

indices = [3, 5, 9, 13, 18]
my_list = ['a', 'b', 'c', ..., 'x', 'y', 'z']

因此,基本上,将my_list从范围中分割出来:

So basically, split my_list from range:

my_list[:3], mylist[3:5], my_list[5:9], my_list[9:13], my_list[13:18], my_list[18:]

我尝试将索引索引为2,但是结果不是我所需要的.

I have tried to indices into chunks of 2 but the result is not what i need.

[indices[i:i + 2] for i in range(0, len(indices), 2)]

我的实际列表长度是1000.

My actual list length is 1000.

推荐答案

您也可以使用简单的python来做到这一点.

You could also do it using simple python.

indices = [3, 5, 9, 13, 18]
my_list = list('abcdefghijklmnopqrstuvwxyz')

解决方案

使用列表理解.

Solution

Use list comprehension.

[my_list[slice(ix,iy)] for ix, iy in zip([0]+indices, indices+[-1])]

输出

[['a', 'b', 'c'],
 ['d', 'e'],
 ['f', 'g', 'h', 'i'],
 ['j', 'k', 'l', 'm'],
 ['n', 'o', 'p', 'q', 'r'],
 ['s', 't', 'u', 'v', 'w', 'x', 'y']]

检查是否提取了正确的索引顺序

dict(((ix,iy), my_list[slice(ix,iy)]) for ix, iy in zip([0]+indices, indices+[-1]))

输出

{(0, 3): ['a', 'b', 'c'],
 (3, 5): ['d', 'e'],
 (5, 9): ['f', 'g', 'h', 'i'],
 (9, 13): ['j', 'k', 'l', 'm'],
 (13, 18): ['n', 'o', 'p', 'q', 'r'],
 (18, -1): ['s', 't', 'u', 'v', 'w', 'x', 'y']}

这篇关于根据另一个列表的索引将列表拆分为块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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