How can I slice the list to get every 2 consecutive list items in new lists?

Let's say you have a list [1,2,3,...,99,100]

import numpy as np
ls = np.linspace(1,100,100)

      

Say you are playing with musical notation to find the ones that work for you.

print(ls[:2])
>> [ 1.  2.]

print(ls[::2])
>> [  1.   3.   5.   7.  ...  97.  99.]

      

How can I slice the data in such a way as to get

[1,2],[3,4],[5,6],[7,8],...,[99,100]

      

##

maybe not important, but my goal is to adapt this to my dataset, where the values ​​in the lists indicate the numeric index of another list of values ​​(other_values ​​[index]) to be matched. Can slicing be combined with arrays?

+3


source to share


2 answers


You can use a parameter .resize(..,2)

. The result is ls

now a numpy array with 50 times; 2 dimensions:



>>> ls.resize(ls.shape[0]/2,2)
>>> ls
array([[   1.,    2.],
       [   3.,    4.],
       [   5.,    6.],
       [   7.,    8.],
       [   9.,   10.],
       [  11.,   12.],
       [  13.,   14.],
       [  15.,   16.],
       [  17.,   18.],
       [  19.,   20.],
       [  21.,   22.],
       [  23.,   24.],
       [  25.,   26.],
       [  27.,   28.],
       [  29.,   30.],
       [  31.,   32.],
       [  33.,   34.],
       [  35.,   36.],
       [  37.,   38.],
       [  39.,   40.],
       [  41.,   42.],
       [  43.,   44.],
       [  45.,   46.],
       [  47.,   48.],
       [  49.,   50.],
       [  51.,   52.],
       [  53.,   54.],
       [  55.,   56.],
       [  57.,   58.],
       [  59.,   60.],
       [  61.,   62.],
       [  63.,   64.],
       [  65.,   66.],
       [  67.,   68.],
       [  69.,   70.],
       [  71.,   72.],
       [  73.,   74.],
       [  75.,   76.],
       [  77.,   78.],
       [  79.,   80.],
       [  81.,   82.],
       [  83.,   84.],
       [  85.,   86.],
       [  87.,   88.],
       [  89.,   90.],
       [  91.,   92.],
       [  93.,   94.],
       [  95.,   96.],
       [  97.,   98.],
       [  99.,  100.]])

      

+5


source


something like

list(zip(l[::2], l[1::2]))

      



returns a list of tuples with the desired pairing

+2


source







All Articles