Define a function split_into_k
which takes a list l
of length n
and an integer k
and splits the list l
into a list of k
sublists of length n // k
.
def split_into_k(l, k):
n = len(l)
m = n // k
return [l[i*m:(i+1)*m] for i in range(k)]
Examples with a list of length 12:
sage: A = [1, 2, 3, 4, 6, 8, 2, 7, 9, 0, -1, -2]
Split it into 3 or 4:
sage: split_into_k(A, 3)
[[1, 2, 3, 4], [6, 8, 2, 7], [9, 0, -1, -2]]
sage: split_into_k(A, 4)
[[1, 2, 3], [4, 6, 8], [2, 7, 9], [0, -1, -2]]
If k
does not divide len(l)
, the trailing part
is removed.
sage: split_into_k(A, 5)
[[1, 2], [3, 4], [6, 8], [2, 7], [9, 0]]
Other options would be to raise an exception
or to have a shorter last part.
In case the goal is to construct a matrix: if provided
the desired matrix size, the matrix constructor can eat
a non-nested list of values.
Examples using the list A
above:
sage: A = [1, 2, 3, 4, 6, 8, 2, 7, 9, 0, -1, -2]
sage: a = matrix(ZZ, 3, 4, A)
sage: a
[ 1 2 3 4]
[ 6 8 2 7]
[ 9 0 -1 -2]
sage: b = matrix(ZZ, 4, 3, A)
sage: b
[ 1 2 3]
[ 4 6 8]
[ 2 7 9]
[ 0 -1 -2]
This opens up other ways to write the function split_into_k
.
For instance:
def split_into_k(A, k):
return [list(row) for row in matrix(k, len(A) // k, A)]
Example:
sage: split_into_k(A, 3)
[[1, 2, 3, 4], [6, 8, 2, 7], [9, 0, -1, -2]]
sage: split_into_k(A, 4)
[[1, 2, 3], [4, 6, 8], [2, 7, 9], [0, -1, -2]]
Note that the resulting lists might have slight differences,
as all elements will now be part of a same ring.
For instance if there was one rational but non-integer entry
in the initial list, all elements of the nested lists returned
by this version of split_into_k
will now be rationals.