如果索引范围超出范围,请重复列表

Nic*_*mer 2 python

我有一个Python列表

a = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我想获得一个索引范围,例如,如果我选择指数0经过N,我得到(对N=10)重复

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2]
Run Code Online (Sandbox Code Playgroud)

我当然可以(int(float(N) / len(a) - 0.5) + 1) * a先重复列表并选择其中的范围[0:10],但这感觉相当笨拙.

任何提示?

Sve*_*ach 6

您可以在访问列表时使用模运算符,即

a[i % len(a)]
Run Code Online (Sandbox Code Playgroud)

这将给出相同的结果,但不需要实际存储冗余元素.