问题
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 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
回答1:
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]
回答2:
Use a comprehension:
>>> [a[x:y] for x,y in zip(indx,[*indx[1:], None])]
[['a', 'b', 3, 4, 'd'], [6, 7], [8]]
回答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.
回答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]
回答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]
回答6:
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]
来源:https://stackoverflow.com/questions/55949247/how-to-get-subset-of-list-from-index-of-list-in-python