Reputation:
Is there a pythonic (please no numpy!) way to select a subset list-of-lists from a list-of-lists? In MATLAB, the behavior I'm trying to mimic can be exemplified with something like A(2:7, 5:8)
.
This isn't a homework problem, just looking for a clean solution.
Here's a concrete example:
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
select(A, (1, 3), (0, 3))
should yield
[[2, 3], [5, 6], [8, 9]]
Upvotes: 1
Views: 2368
Reputation: 1121406
You can pass arguments to slices:
def select(lst, subselect, select):
return [sublst[slice(*subselect)] for sublst in lst[slice(*select)]]
Demo:
>>> def select(lst, subselect, select):
... return [sublst[slice(*subselect)] for sublst in lst[slice(*select)]]
...
>>> A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> select(A, (1, 3), (0, 3))
[[2, 3], [5, 6], [8, 9]]
You can even use None
to indicate default values for slicing (so 0
for start
and the length of the input list for the stop
argument) or pass in just one argument to specify a stop
argument:
>>> select(A, (1, None), (3,))
[[2, 3], [5, 6], [8, 9]]
and a third argument gives you the option to specify a stride. If the stride is negative, the list is reversed:
>>> select(A, (1, None), (None, 3, 2))
[[2, 3], [8, 9]]
>>> select(A, (1, None), (None, None, -1))
[[8, 9], [5, 6], [2, 3]]
Upvotes: 4
Reputation: 19766
select(A, (1, 3), (0, 3))
can be implemented as [x[1:3] for x in A[0:3]]
>>> A = [1, 2, 3],[4, 5, 6],[7, 8, 9]
>>> [x[1:3] for x in A[0:3]]
[[2, 3], [5, 6], [8, 9]]
>>>
Upvotes: 0