简体   繁体   中英

Python: Get next element from the list based on input?

I have a list

elem_list = ['a','b','c','d']

I'm trying to get next element from the list based on input

input_val = 'c'
out_data = 'd'

input_val = 'a'
out_data = 'b'

input_val = 'd'
out_data = ''

Assuming that input_val is guaranteed to be present exactly once in the list, you can use:

out_data = ''
elem_index = elem_list.index(input_val)
if elem_index != len(elem_list)-1:
    out_data = elem_list[elem_index+1]

Here, you are first finding the index of the input in the list, and setting the output to be the value at the next index unless it is the last element, in which case you set it as the empty string.

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