从以下数组中我如何得到所述的输出
arr=["harry","sally","tom"]
harry
harry
harry
sally
sally
tom
sally
sally
sally
tom
tom
harry
tom
tom
tom
harry
harry
sally
我尝试了什么
>>> for i in range(len(arr)):
... print arr[i] * 3
... print arr[i+1]*2
... print arr[i-1]
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
IndexError: list index out of range
答案 0 :(得分:3)
使用模数运算符环绕列表的开头,或者将列表加倍,但使用原始的长度。
答案 1 :(得分:2)
>>> for i in range(len(arr)):
print arr[i % len(arr)] * 3
print arr[(i+1) % len(arr)] * 2
print arr[(i+2) % len(arr)] * 1