列表中每隔n个项目获取一个项目块 [英] get a chunk of items every n items in list

查看:123
本文介绍了列表中每隔n个项目获取一个项目块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下列表:

l = [4,3,1,5,3,5,8,11,10,4,12,2,1]

切片l以获得长度n的块的最Python方式是什么?

What is the most pythonic way to slice l in order to get chunks of length n leaving k items between chunks?

例如,如果n=2k=3,结果应为:

For example, if n=2 and k=3 the result should be:

[4,3,5,8,12,2]

推荐答案

使用列表理解:

[e for i in range(0, len(l), n+k) for e in l[i:i+n]]
# [4, 3, 5, 8, 12, 2]

numpy解决方案是:

import numpy as np

idx = (np.arange(0, len(l), n+k)[:,None] + np.arange(n)).ravel()
np.array(l)[idx]
# array([ 4,  3,  5,  8, 12,  2])

这篇关于列表中每隔n个项目获取一个项目块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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