Reputation: 21
I have a list l=[[[1,2,3],[4,5,6]],[[7,8,9],[9,1,2]]]
How do I get the list [[[1,2],[4,5]],[[7,8],[9,1]]]
using just slicing? I tried l[:][:][:2]
but it gave me the entire 3d list.
Upvotes: 2
Views: 135
Reputation: 53029
Update: just noticed your outer lists do not need slicing. In that case:
Since you are on Python2 map
works well on this one:
>>> from operator import itemgetter
>>> ft = itemgetter(slice(2))
>>>
>>> map(map, (ft, ft), l)
[[[1, 2], [4, 5]], [[7, 8], [9, 1]]]
The solution below was wrongly assuming the input list was 3 x 3 x 3
and to be sliced to 2 x 2 x 2
. I'll leave it here in case anybody is looking for that case.
>>> from operator import itemgetter
>>> ft = itemgetter(slice(2))
>>>
>>> map(map, (ft, ft), map(ft, l[:2]))
[[[1, 2], [4, 5]], [[7, 8], [9, 1]]]
Upvotes: 1
Reputation: 41168
You could use a nested list comprehension, of course this ins't only using slicing but hopefully still useful:
>>> lst = [[[1,2,3],[4,5,6]],[[7,8,9],[9,1,2]]]
>>> [[subsub[:-1] for subsub in sublist] for sublist in lst]
[[[1, 2], [4, 5]], [[7, 8], [9, 1]]]
Upvotes: 1