slicing list of lists in Python

后端 未结 6 1524
旧巷少年郎
旧巷少年郎 2020-12-10 14:40

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

6条回答
  •  醉梦人生
    2020-12-10 14:54

    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 [4]: A[:,:3].tolist()
    Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    

提交回复
热议问题