python - adaptable function to slice up nested lists? -
if have square matrix nested list in python can split several equal sized boxes , create new list each element list of numbers in 1 of boxes. e.g.
a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15 ,16]] b = [[a[0][0], a[0][1], a[1][0], a[1][1]], [a[0][2], a[0][3], a[1][2], a[1][3]], [a[2][0], a[2][1], a[3][0], a[3][1]], [a[2][2], a[2][3], a[3][2], a[3][3]]]
is there easier way this? there way set function can apply matrices of different sizes , specify size of boxes?
the next equivalent have , bit more concise:
b = [a[0][:2] + a[1][:2], a[0][2:] + a[1][2:], a[2][:2] + a[3][:2], a[2][2:] + a[3][2:]]
or equivalent list comprehension:
b = [a[i][s] + a[i+1][s] in (0,2) s in (slice(none,2), slice(2,none))]
python list nested-lists
No comments:
Post a Comment