Python:将列表中的元素向右移动并将列表末尾的元素移动到开头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29498418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Shifting elements in a list to the right and shifting the element at the end of the list to the beginning
提问by nesman
I want to rotate elements in a list, e.g. - shift the list elements to the right so ['a','b','c','d']
would become ['d','a','b','c']
, or [1,2,3]
becomes [3,1,2]
.
我想旋转列表中的元素,例如 - 将列表元素向右移动,这样['a','b','c','d']
就会变成['d','a','b','c']
,或者[1,2,3]
变成[3,1,2]
。
I tried the following, but it's not working:
我尝试了以下方法,但它不起作用:
def shift(aList):
n = len(aList)
for i in range(len(aList)):
if aList[i] != aList[n-1]:
aList[i] = aList[i+1]
return aList
elif aList[i] == aList[i-1]:
aList[i] = aList[0]
return aList
shift(aList=[1,2,3])
回答by aldeb
If you are trying to shift the elements, use collections.deque
rotate
method:
如果您尝试移动元素,请使用方法:collections.deque
rotate
#! /usr/bin/python3
from collections import deque
a = deque([1, 2, 3, 4])
a.rotate()
print(a)
Result:
结果:
[2, 3, 4, 1]
回答by Padraic Cunningham
If you actually want to shift the elements, you can use modulo to cycle the list and reassign the elements to their shifted positions:
如果你真的想要移动元素,你可以使用 modulo 循环列表并将元素重新分配到它们的移动位置:
def shift(lst, shft=0):
ln = len(lst)
for i, ele in enumerate(lst[:]):
lst[(i + shft) % ln] = ele
return lst
In [3]: shift( ['a','b','c','d'] , 1)
Out[3]: ['d', 'a', 'b', 'c']
In [4]: shift( ['a','b','c','d'] , 2)
Out[4]: ['c', 'd', 'a', 'b']
In [5]: shift( ['a','b','c','d'] , 3)
Out[5]: ['b', 'c', 'd', 'a']
If you only want a single shift just shift the last element to the front extending the list:
如果您只想要一个移位,只需将最后一个元素移到扩展列表的前面:
def shift(lst):
lst[0:1] = [lst.pop(),lst[0]]
return lst
Both of which change the original list.
两者都更改了原始列表。
回答by ?ukasz Rogalski
Simple use of slice syntax:
切片语法的简单使用:
def shift(seq):
return [seq[-1]] + seq[:-1]
assert shift([1, 2, 3, 4, 5]) == [5, 1, 2, 3, 4]
Generalized version with changeable shift:
具有可变移位的通用版本:
def shift(seq, shift=1):
return seq[-shift:] + seq[:-shift]
assert shift([1, 2, 3, 4, 5]) == [5, 1, 2, 3, 4]
assert shift([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]
回答by Malik Brahimi
Use a function assuming n
is the shift that is less than the length of list l
like so:
使用一个函数,假设n
是小于列表长度的移位,l
如下所示:
shift = lambda l, n: l[-n:] + l[:-n] # i.e. shift([1, 2, 3, 4], 3)
回答by mkrieger1
You can use negative indices together with list concatenation:
您可以将负索引与列表连接一起使用:
def shift(seq, n=0):
a = n % len(seq)
return seq[-a:] + seq[:-a]
回答by xnx
The question seems to imply to me that the list itself should be modified rather than a new list created. A simple in placealgorithm is therefore:
这个问题对我来说似乎暗示应该修改列表本身而不是创建新列表。因此,一个简单的就地算法是:
lst = [1, 2, 3, 4, 5]
e1 = lst[-1]
for i, e2 in enumerate(lst):
lst[i], e1 = e1, e2
print(lst)
Giving:
给予:
[5, 1, 2, 3, 4]
回答by dotancohen
You can just slice the last element off the list, then add it to the beginning of a new list:
您可以将列表中的最后一个元素切片,然后将其添加到新列表的开头:
aList = [aList[-1]] + aList[:-1]
Here is the result:
结果如下:
>>> aList = [1,2,3]
>>> aList = [aList[-1]] + aList[:-1]
>>> aList
[3, 1, 2]
回答by Rob?
If you are allergic to slice notation: a.insert(0,a.pop())
如果您对切片符号过敏: a.insert(0,a.pop())
Usage:
用法:
In [15]: z=[1,2,3]
In [16]: z.insert(0,z.pop())
In [17]: z
Out[17]: [3, 1, 2]
In [18]: z.insert(0,z.pop())
In [19]: z
Out[19]: [2, 3, 1]
回答by Qirui
This could be done simply by using list method: insert,
这可以通过使用列表方法简单地完成:插入,
values = [2, 3, 5, 7, 11, 13]
def shift(list):
new_list = []
for i in list:
new_list.insert(len(new_list)-1, i)
return new_list
print(shift(values))
打印(移位(值))
Output is:
输出是:
[3, 5, 7, 11, 13, 2]
回答by Srivatsa Sheshadri
You can use this:
你可以使用这个:
li=li[-1:]+li[:-1]