Reputation: 1
I have a list of let's say [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
and its name is somelist
. I want to do somelist[:2][:2]
and have that return [[1,2], [1,2]]
. So it slices the list and then slices that list and returns that. Is it even possible to do this in one line in python?
Upvotes: 0
Views: 1357
Reputation: 25416
Multidimensional slicing is easy with numpy:
import numpy
a = numpy.array([[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]])
print(a[:2,:2])
Upvotes: 1
Reputation: 4477
Are your lists always 16 elements in a 4x4 matrix? If you are simply trying to get the 4 lower right corner elements, try:
>>> l = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
>>> print [l[2][:2], l[3][:2]]
[[1, 2], [1, 2]]
Otherwise, for a general solution the list comprehension mentioned by others is better.
It would be interesting to benchmark both and see which is faster for your use case. Though this sounds like premature optimization to me.
Upvotes: 0
Reputation: 2616
You can do this using list comprehension. I changed your sample input to make it clearer what is being selected:
>>> l = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> print [x[:2] for x in l[:2]]
[[1, 2], [5, 6]]
Upvotes: 8