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 indx=[0,5,7] # index list a = ['a', 'b', 3, 4, 'd', 6, 7, 8] I need to get
Solution 1:
Use a comprehension:
>>> [a[x:y] for x,y in zip(indx,[*indx[1:], None])]
[['a', 'b', 3, 4, 'd'], [6, 7], [8]]
Solution 2:
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]
Solution 3:
results = [a[indx[i]:indx[i+1]] for i in range(len(indx)-1)]
Will return a list containing the 3 lists you want.
Solution 4:
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.
indx=[0,5,7] # index list
a = ['a', 'b', 3, 4, 'd', 6, 7, 8]
if indx[0] != 0:
indx = [0] + indx #fixes left indexing in case 0 is not present
if indx[-1] != len(a):
indx += [len(a)] #fixes right indexing to make sure you get all values from the list.
print(indx) #[0, 5, 7, 8]
for left, right in zip(indx, indx[1:]):
print(a[left: right])
#Output:
['a', 'b', 3, 4, 'd']
[6, 7]
[8]
Solution 5:
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]
Post a Comment for "How To Get Subset Of List From Index Of List In Python"