0

从以下数组中,我如何获得所述的输出

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
4

2 回答 2

3

使用模运算符环绕到列表的开头,或者将列表加倍但使用原始长度。

于 2012-10-05T13:38:52.317 回答
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
于 2012-10-05T13:44:10.910 回答