Get subset of list Python

how to get subset of list from index of list in python

I had a list of strings, I need to subset from the list based on their indexes list in generic manner

I need to get subsets in generic manner in first iteration:

a[0:5]

2nd iteration:

a[5:7]

3rd iteration:

a[7:]

The code I have tried:

for i in indx: if len[indx]==i: print[a[i:]] else: print[a[i:i+1]]

Expected output:

a[0:5]=='a', 'b', 3, 4, 'd' a[5:7]=6, 7 a[7:]=8

You can try this :

indx.append[len[a]] print[*[a[i:j] for i,j in zip[indx, indx[1:]]], sep='\n']

OUTPUT :

['a', 'b', 3, 4, 'd'] [6, 7] [8]

Use a comprehension:

>>> [a[x:y] for x,y in zip[indx,[*indx[1:], None]]] [['a', 'b', 3, 4, 'd'], [6, 7], [8]]
results = [a[indx[i]:indx[i+1]] for i in range[len[indx]-1]]

Will return a list containing the 3 lists you want.

You were right in thinking of iterating through two items at once, but the issue is that for i in lst does not use indexes, and will fail.

One way to iterate and take two items is by using zip.

Here you go.

for i in range[len[indx]]: try: print["a[%s:%s] ==" % [indx[i], indx[i + 1]] + " ", end=" "] print[a[indx[i]:indx[i + 1]]] except IndexError: print["a[%s:] ==" % [indx[i]] + " ", end=" "] print[a[indx[i]:]]

Output:

a[0:5] == ['a', 'b', 3, 4, 'd'] a[5:7] == [6, 7] a[7:] == [8]

You can use the slice type to convert your index list into list slices. As others have already posted, use zip to create the start-finish pairs:

>>> print[list[zip[indx, indx[1:]+[None]]]] [[0, 5], [5, 7], [7, None]]

We use these pairs to define slices:

>>> slices = [slice[a, b] for a, b in zip[indx, indx[1:]+[None]]]

Then use the slice object just like you would an integer index, but the slice will select the list substring as defined in the slice start-finish pair:

>>> for slc in slices: ... print[a[slc]]

Gives:

['a', 'b', 3, 4, 'd'] [6, 7] [8]

Video liên quan

Chủ Đề