将列表切成子列表的列表 [英] Slicing a list into a list of sub-lists
问题描述
对于任意长度的子列表,将列表切成切片的子列表节列表的最简单且合理有效的方法是什么?
What is the simplest and reasonably efficient way to slice a list into a list of the sliced sub-list sections for arbitrary length sub lists?
例如,如果我们的来源列表为:
For example, if our source list is:
input = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... ]
我们的子列表长度为3,然后我们寻求:
And our sub list length is 3 then we seek:
output = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ... ]
同样,如果我们的子列表长度为4,则我们寻求:
Likewise if our sub list length is 4 then we seek:
output = [ [1, 2, 3, 4], [5, 6, 7, 8], ... ]
推荐答案
[input[i:i+n] for i in range(0, len(input), n)] # Use xrange in py2k
其中n
是块的长度.
由于当input
中的元素数不能被n
整除时,由于您没有定义新列表的最后一个元素可能发生的情况,因此我认为这并不重要:使用此方法,您将例如,如果n
等于7,则最后一个元素等于2.
Since you don't define what might happen to the final element of the new list when the number of elements in input
is not divisible by n
, I assumed that it's of no importance: with this you'll get last element equal 2 if n
equal 7, for example.
这篇关于将列表切成子列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!