简体   繁体   中英

Finding last element index based on condition

I have a list of strings, eg

lst = ['2', '\n', '4', '\n', '\n']

I'm trying to determine the index point of the last string element that is not '\\n'. In the above example the index point would be 2 as '4' is the last element whose value is not '\\n'.

I can find the first occurance of '\\n' easy etc:

lst.index('\n') 

Is there a way to find the last occurance of an element that IS NOT of a particular string char?

You can use next with enumerate , then subtract the result from the length of your list:

lst = ['2', '\n', '4', '\n', '\n']
idx = len(lst) - next(i for i, val in enumerate(reversed(lst), 1) if val != '\n')  # 2

Or, as proposed by @Chris_Rands, iterate backwards via a range that counts down:

idx = next(i for i in range(len(lst)-1, -1, -1) if lst[i] != '\n')  # 2

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