简体   繁体   中英

How to slice a list that is sliced in python?

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?

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]]

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])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM