循环列表的值 [英] Cycling values of a list

查看:61
本文介绍了循环列表的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to coding and am trying to write a simple code that will take a list, say [1,2,3] and cycle the elements n number of times. So if n=1, I should get A=[3,1,2]. If n=2, I should get A=[2,3,1].The code I have written is:

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的值是多少,我都会得到相同的答案,该答案仅循环一次.我认为问题在于循环每次都循环通过相同的B,因此我需要将新的B存储为其他东西,然后用新的B重复循环.但是我不知道该怎么做.任何提示将不胜感激

The problem is that no matter what the value of n is I get the same answer which is only cycled once. I think the problem is that the loop is cycling through the same B every time, so I need to store the new B as something else and then repeat the loop with new B. But I can't figure out how to do that. Any tips would be appreciated

推荐答案

我认为您过于复杂了.考虑将其更改为以下内容:

I think you're overcomplicating it. Consider changing it to something like the following:

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]

In case of n=1, you get [3, 1, 2], and n=2 gives you [2, 3, 1]

请注意,您要执行的操作是在 numpy.roll 中实现的(我想您是在询问过程,而不是结果,只是为了以防万一)

Note that what you are trying to do is implemented in numpy.roll (I suppose you're asking about the process, not the result, but just in case)

import numpy as np

>>> np.roll(A,1)
array([3, 1, 2])
>>> np.roll(A,2)
array([2, 3, 1])

这篇关于循环列表的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆