简体   繁体   English

在列表中向前移动元素

[英]Shifting elements forward in a list

I am trying to do the following; 我正在尝试执行以下操作; [1,2,3,4] -> [1,1,2,3] [1,2,3,4] -> [1,1,2,3]

Here is my attempt, but not working. 这是我的尝试,但无济于事。 I want to modify this in place. 我想在此进行修改。

A = [1,2,3,4]
temp = A[0]
for i in range(1, len(A)-2):
    A[i] = temp
    temp = A[i]

But instead I am getting back [1,1,3,4] . 但是相反,我回来了[1,1,3,4] I want to do backward as well, but so far I can't shift by one forward. 我也想做后退,但到目前为止我不能前进一个。

Unless I'm missing something, perhaps some simple list slicing and assignment is all you need? 除非我缺少任何内容,否则您只需要一些简单的列表切片和分配?

A[1:] = A[:-1]
A
# [1, 1, 2, 3]

Similarly, shifting backward by 1 would be 同样,向后移1将是

A[:-1] = A[1:]

In general, to shift by N, use: 通常,要移动N,请使用:

A[n:] = A[:-n]

Shifting forward by 1 can also be done with a for loop and a temp variable: 也可以使用for循环和temp变量来向前移动1:

temp = A[0]
for i in range(len(A)-1):
    temp, A[i+1] = A[i+1], temp

A
# [1, 1, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM