문제

If we have a list:

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

What is the pythonic way of making the indexation of a list cyclic? Meaning i can never get indexError. And i need the indexation, therefore i can't use cycle with next
For example:

>>>myList[6]
2
>>>myList[-6]
5
도움이 되었습니까?

해결책

You can use modulus operator, like this

myList = [1, 2, 3, 4, 5]
print myList[6  % len(myList)]
# 2
print myList[-6 % len(myList)]
# 5
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top