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?
-
Sure, it possible in one line, but the syntax you're trying to use specifies the first two elements in the list, then the first two elements again; you want a slice on each of the members. Anyway, this belongs on SO and will be migrated shortly.Shane Madden– Shane Madden2011-06-26 00:15:18 +00:00Commented Jun 26, 2011 at 0:15
-
...or somebody might just answer it here. You never know.larsks– larsks2011-06-26 00:28:19 +00:00Commented Jun 26, 2011 at 0:28
Add a comment
|
3 Answers
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]]
Comments
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])
Comments
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.