列表的循环值

Dea*_*een 9 python for-loop list python-3.x

我是编码的新手,我正在尝试编写一个简单的代码来获取列表,例如[1,2,3]并循环元素n次.所以如果n = 1,我应该得到A = [3,1,2].如果n = 2,我应该得到A = [2,3,1].我写的代码是:

n=1
j=0
A = [1,2,3]
B = [None]*len(A)

while j<=n:
     for i in range(0,len(A)):
         B[i] = A[-1+i]
     j=j+1
print(B)
Run Code Online (Sandbox Code Playgroud)

问题是,无论n的值是什么,我都得到相同的答案,只能循环一次.我认为问题是循环每次都在同一个B中循环,所以我需要将新B存储为其他东西,然后用新的B重复循环.但我无法弄清楚如何做到这一点.任何提示将不胜感激

sac*_*cuL 6

我觉得你过于复杂了.考虑将其更改为以下内容:

n = 1
A = [1,2,3]
B = A.copy()

for _ in range(n):
    # Cycle through by concatenating the last element and all other elements together 
    B = [B[-1]]+B[0:-1]

print(B)
Run Code Online (Sandbox Code Playgroud)

万一n=1,你得到[3, 1, 2],并n=2给你[2, 3, 1]

请注意,您正在尝试执行的操作numpy.roll(我想您要询问的是流程,而不是结果,但以防万一)

import numpy as np

>>> np.roll(A,1)
array([3, 1, 2])
>>> np.roll(A,2)
array([2, 3, 1])
Run Code Online (Sandbox Code Playgroud)


Stu*_*art 5

一个更简单的功能是:

def roll(L, n):
    n %= len(L)
    return L[-n:] + L[:-n]

A = [1,2,3]
roll(A, 1)   # [3, 1, 2]
roll(A, 2)   # [2, 3, 1]
roll(A, 3)   # [1, 2, 3]
roll(A, 4)   # [3, 1, 2]
Run Code Online (Sandbox Code Playgroud)

采用模数(n %= len(L))避免了保持循环的需要.然后,我们只是将列表末尾的适当大小的片段连接到它的开头.