我有一个列表 a
,我需要从位置 2 迭代到其上一个位置 1。
# old index - 0 1 2 3 4
a = [1,2,3,4,5]
# new index - 2,3,4,0,1
# new value - 3,4,5,1,2
cnt = 0
while True:
for i in range(2,len(a)):
print(a[i])
for i in range(len(a)-2-1):
print(a[i])
break
我使用了 2 个 for 循环,但我相信应该有更好的方法来做到这一点。
最佳答案
假设我们从一个列表 a = [1,2,3,4,5]
开始。
您可以使用collections.deque
及其方法deque.rotate
:
from collections import deque
b = deque(a)
b.rotate(-2)
print(b)
deque([3, 4, 5, 1, 2])
或者,如果您愿意使用第 3 方库,则可以使用 NumPy 和 np.roll
:
import numpy as np
c = np.array(a)
c = np.roll(c, -2)
print(c)
array([3, 4, 5, 1, 2])
关于python - 迭代 python 循环直到上一个位置的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964824/