在Python中,如何将列表从前一个块中的最后一个元素开始分成大小均匀的块? [英] In Python how do you split a list into evenly sized chunks starting with the last element from the previous chunk?

查看:58
本文介绍了在Python中,如何将列表从前一个块中的最后一个元素开始分成大小均匀的块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转换列表之类的最Python方式是什么:

What would be the most pythonic way to convert a list like:

mylist = [0,1,2,3,4,5,6,7,8]

放入n元素的块中,该块始终从上一个块的最后一个元素开始. 最后一块的最后一个元素应与第一个块的第一个元素相同,以使数据结构呈圆形. 喜欢:

into chunks of n elements that always start with the last element of the previous chunk. The last element of the last chunk should be identical to the first element of the first chunk to make the data structure circular. Like:

[
[0,1,2,3],
[3,4,5,6],
[6,7,8,0],
]

假设len(mylist) % (n-1) == 0.这样它总是可以很好地工作.

under the assumption that len(mylist) % (n-1) == 0 . So that it always works nicely.

推荐答案

直接解决方案怎么样?

splitlists = [mylist[i:i+n] for i in range(0, len(mylist), n-1)]
splitlists[-1].append(splitlists[0][0])

这篇关于在Python中,如何将列表从前一个块中的最后一个元素开始分成大小均匀的块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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