slicing list of lists in Python
问题 I need to slice a list of lists in python. A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]] idx = slice(0,4) B = A[:][idx] The code above isn't giving me the right output. What I want is : [[1,2,3],[1,2,3],[1,2,3]] 回答1: With numpy it is very simple - you could just perform the slice: In [1]: import numpy as np In [2]: A = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]) In [3]: A[:,:3] Out[3]: array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) You could, of course, transform numpy.array back to the list : In