slicing list of lists in Python

后端 未结 6 1525
旧巷少年郎
旧巷少年郎 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:47

    you can use a list comprehension such as: [x[0:i] for x in A] where i is 1,2,3 etc based on how many elements you need.

    0 讨论(0)
  • 2020-12-10 14:53
    A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
    
    print [a[:3] for a in A]
    

    Using list comprehension

    0 讨论(0)
  • 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]]
    
    0 讨论(0)
  • 2020-12-10 14:58

    I am new in programming and Python is my First Language. it's only 4 to 5 days only to start learning. I just learned about List and slicing and looking for some example I found your problem and try to solve it Kindly appreciate if my code is correct. Here is my code A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]] print(A[0][0:3],A[1][0:3],A[1][0:3])

    0 讨论(0)
  • 2020-12-10 15:00

    Either:

    >>> [a[slice(0,3)] for a in A]
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    

    Or:

    >>> [list(filter(lambda x: x<=3, a)) for a in A]
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    
    0 讨论(0)
  • 2020-12-10 15:09

    Very rarely using slice objects is easier to read than employing a list comprehension, and this is not one of those cases.

    >>> A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
    >>> [sublist[:3] for sublist in A]
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    

    This is very clear. For every sublist in A, give me the list of the first four elements.

    0 讨论(0)
提交回复
热议问题