如何实现输入列表元素后选中下一个,末尾元素则选中首个元素?
实现循环获取列表下一个元素的方案
核心思路是利用列表索引 + 取模运算实现循环逻辑:
- 先定位输入元素在列表中的索引位置
- 通过取模运算计算下一个索引,自动处理最后一个元素跳转到第一个元素的场景
完整代码示例:
exchange_list = ['coin', 'quarter', 'dime', 'penny', 'buck', 'bitcoin'] exchanger = input("Please give the input of a money currency that you'd like to exchange: ") # 校验输入是否在列表内 if exchanger in exchange_list: current_index = exchange_list.index(exchanger) # 取模运算实现循环索引,无需额外判断是否为最后一个元素 next_index = (current_index + 1) % len(exchange_list) next_currency = exchange_list[next_index] print(f"对应的兑换货币是: {next_currency}") else: print("输入的货币不在可兑换列表中,请重新输入")
代码说明
exchange_list.index(exchanger):获取输入元素在列表中的索引(current_index + 1) % len(exchange_list):取模运算确保索引始终在列表范围内,当当前索引是最后一个时,计算结果为0,刚好对应列表第一个元素- 增加输入校验,避免输入不在列表中的元素引发错误
内容的提问来源于stack exchange,提问作者TahaAvadi
相关产品推荐
相关产品推荐

