gpt4 book ai didi

python - 如何在 python 中使列表的索引循环?

转载 作者:行者123 更新时间:2023-11-28 21:55:20 26 4
gpt4 key购买 nike

如果我们有一个列表:

myList = [1,2,3,4,5]

使列表循环索引的 pythonic 方法是什么?这意味着我永远无法获得 indexError。而且我需要索引,因此我不能将 cyclenext
一起使用例如:

>>>myList[6]
2
>>>myList[-6]
5

最佳答案

你可以像这样使用模运算符

myList = [1, 2, 3, 4, 5]
print myList[6 % len(myList)]
# 2
print myList[-6 % len(myList)]
# 5

关于python - 如何在 python 中使列表的索引循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22841716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com