[英]Python: How to split a list into ordered chunks
If I have the following list如果我有以下列表
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Then然后
np.array_split([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)
Returns退货
[array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
Is there a way to get the sub-arrays in the following order?有没有办法按以下顺序获取子数组?
[array([0, 3, 6, 9]), array([1, 4, 7]), array([2, 5, 8])]
As the lists are of differing lengths, a numpy.ndarray
isn't possible without a bit of fiddling, as all sub-arrays must be the same length.由于列表的长度不同,
numpy.ndarray
是不可能的,因为所有子数组的长度必须相同。
However, if a simple list
meets your requirement, you can use:但是,如果一个简单的
list
满足您的要求,您可以使用:
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l2 = []
for i in range(3):
l2.append(l[i::3])
Output: Output:
[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]
Or more concisely, giving the same output:或者更简洁,给出相同的 output:
[l[i::3] for i in range(3)]
Let's look into source code refactor of np.array_split
:让我们看看
np.array_split
的源代码重构:
def array_split(arr, Nsections):
Neach_section, extras = divmod(len(arr), Nsections)
section_sizes = ([0] + extras * [Neach_section + 1] + (Nsections - extras) * [Neach_section])
div_points = np.array(section_sizes).cumsum()
sub_arrs = []
for i in range(Nsections):
st = div_points[i]
end = div_points[i + 1]
sub_arrs.append(arr[st:end])
return sub_arrs
Taking into account your example arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
and Nsections = 3
it will construct section sizes [0, 4, 3, 3]
and dividing points [0, 4, 7, 10]
.考虑到您的示例
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
和Nsections = 3
它将构造部分大小[0, 4, 3, 3]
和分割点[0, 4, 7, 10]
。 Then do something like this:然后做这样的事情:
[arr[div_points[i]:div_points[i + 1]] for i in range(3)]
Trying to mimic behaviour of numpy
, indeed,确实,试图模仿
numpy
的行为,
def array_split_withswap(arr, N):
sub_arrs = []
for i in range(N):
sub_arrs.append(arr[i::N])
Is the best option to go with (like in @S3DEV solution).是 go 的最佳选择(如在@S3DEV 解决方案中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.