简体   繁体   中英

How to get list indices after a specific index

If I have the list: ['a', 'b', 'c', 'd', 'e'] , and I want a variable like this: afterC = ['d','e'] - Aka, all items after 'c' get put into their own list. I've tried searching for a solution, but I can't find anything

The list object has an .index() method which returns the index of a given value. This index can be used to slice the list and return the values after the given index.

For example:

l = ['a', 'b', 'c', 'd', 'e']

l2 = l[l.index('c') + 1:]

Output:

>>> l2
['d', 'e']

Documentation linked here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM