Search code examples
python-3.xnumpyindexingvectorization

Python3 extract various subsets from list/array into a single new variable


In matlab for an 1xM array let us say a=1,1.5,2,2.5,...10

a=1:0.5:10;

one can easily extract several subsets of the array in 1 line of code b=a([1:3 10:13]);.

making b=1,1.5,2,5.5,6,6.5,7. If one would like to achieve something equivalent in python3 and numpy, what is the recommended approach? Note the actual vector is of length 1 x 7 and the subsets to extract are of different lengths and random initial and final indexes.


Solution

  • Here is a short answer to that, live from Python in CLI, without numpy:

    # generate your vector a, as only integers are allowed in range()
    >>> b=[x*0.5 for x in range(2,21)]
    >>> b
    [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]
    
    # compose result subset from subsets
    >>> b=a[1:4]+a[10:14]
    >>> b
    [1.5, 2.0, 2.5, 6.0, 6.5, 7.0, 7.5]
    

    Depending on your indexes and limits, the respective final answer can be taken also by using these b=a[start_index:(start_index+4)]+a[end_index:(end_index+4)]