Python 循环列表的值
我对编码还不熟悉,我正在尝试编写一个简单的代码,它将获取一个列表,比如[1,2,3],并循环元素n次。如果n=1,我应该得到A=[3,1,2]。如果n=2,我应该得到A=[2,3,1]。我编写的代码是:Python 循环列表的值,python,python-3.x,list,for-loop,Python,Python 3.x,List,For Loop,我对编码还不熟悉,我正在尝试编写一个简单的代码,它将获取一个列表,比如[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) n=1 j=0 A=[1,2,3]
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)
n=1
j=0
A=[1,2,3]
B=[无]*len(A)
而我认为你把它复杂化了。考虑把它变成如下的东西:
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)
在n=1
的情况下,您将获得[3,1,2]
,而n=2
将为您提供[2,3,1]
请注意,您试图做的是在numpy.roll
中实现的(我想您是在询问过程,而不是结果,只是以防万一)
因为有人已经回答了你的问题,所以没有深入讨论。。但这里需要注意的一个重要特性是
A = [1, 2, 3] #Assuming that the length of the matrix you want to rotate is of length 3
If you want to cycle/rotate by 3, then you want to actually cycle/rotate by `len(A)%3` = 0
If you want to cycle/rotate by 6, then you want to actually cycle/rotate by `len(A)%6` = 0
If you want to cycle/rotate by 4, then you want to actually cycle/rotate by `len(A)%3` = 1
If you want to cycle/rotate by a number lesser than the length itself.. then just rotate it by that number!
so if you want to cycle by 2, then well.. rotate it by two..
@sacul的答案是正确的,但你很接近!在创建新的B
之后,您错过了为while循环的下一次迭代更新A
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]
A = B[:] # update A so that next time B works on the new A
print('A is now ', A) # to debug
j=j+1
print(B)
更简单的功能是:
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]
取模数(n%=len(L)
)可以避免循环。然后,我们只需将一个适当大小的片段从列表的末尾连接到列表的开头。一个基于itertools
的解决方案
from itertools import cycle, islice
def roll(x, n):
start = len(x) - n
return islice(cycle(x), start, start + len(x))
如果我们循环使用x中的值(实际上最多只做两次)。然后切片,使其从我们想要的元素开始,并包含正确数量的元素
它可能比其他一些解决方案更为深奥,但考虑到有如此多的替代方案,它值得一提
itertools.islice
返回一个生成器。如果要打印结果,需要将其转换为列表
查看以了解代码问题。但是,列表
不是这种需求最合适的结构,因为每个班次都有O(n)复杂度
collections
模块中的(“双端队列”)通过其rotate
方法提供此功能。该方法在适当的位置工作并且具有O(k)复杂度,其中k是表示旋转次数的参数。下面是一个例子:
from collections import deque
d = deque([1,2,3])
d.rotate(2)
print(d)
deque([2, 3, 1])
但这是n=1的错误结果。。。设置whilej@Stuart“错”是什么意思j=1
可能意味着2次迭代;这只是定义的问题。这是OP的原始代码,只是稍微修改了一下,以解释他们哪里出错了。错误的意思是它没有为给定的A
和n
提供OP指定的输出。好的,我现在知道了如何像我最初说的那样更新B。我试着说B=A,但我知道如果我交换得到的顺序,我的问题之一是两个列表索引之间的关系是j=(j-n)%k
,其中j
是循环列表索引,k
是列表长度。使用阵列将非常有效。直接索引列表仍然是可以接受的(在python思想中)。然而,对于这样一个常见的问题,必须创建、加入和销毁遍布各地的列表,这让我感到困惑。您可以进一步将B[0:-1]
简化为B[:-1]
from itertools import cycle, islice
def roll(x, n):
start = len(x) - n
return islice(cycle(x), start, start + len(x))
from collections import deque
d = deque([1,2,3])
d.rotate(2)
print(d)
deque([2, 3, 1])