在 Python 列表中移动值但保留顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1212025/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:42:48  来源:igfitidea点击:

Moving values but preserving order in a Python list

pythonlist

提问by sloth

I have a list

我有一个清单

a=[1,2,3,4,5]

and want to 'move' its values so it changes into

并希望“移动”它的值,使其变为

a=[2,3,4,5,1]

and the next step

和下一步

a=[3,4,5,1,2]

Is there a built-in function in Python to do that?

Python 中是否有内置函数可以做到这一点?

Or is there a shorter or nicer way than

或者有比这更短或更好的方法

b=[a[-1]]; b.extend(a[:-1]); a=b

回答by Miles

>>> a = [1,2,3,4,5]
>>> a.append(a.pop(0))
>>> a
[2, 3, 4, 5, 1]

This is expensive, though, as it has to shift the contents of the entire list, which is O(n). A better choice may be to use collections.dequeif it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:

但是,这很昂贵,因为它必须移动整个列表的内容,即 O(n)。collections.deque如果它在您的 Python 版本中可用,则更好的选择可能是使用它,它允许在大约 O(1) 时间内从任一端插入和删除对象:

>>> a = collections.deque([1,2,3,4,5])
>>> a
deque([1, 2, 3, 4, 5])
>>> a.rotate(-1)
>>> a
deque([2, 3, 4, 5, 1])

Note also that both these solutions involve changing the original sequence object, whereas yours creates a new list and assigns it to a. So if we did:

另请注意,这两种解决方案都涉及更改原始序列对象,而您的解决方案会创建一个新列表并将其分配给a. 所以如果我们这样做:

>>> c = a
>>> # rotate a

With your method, cwould continue to refer to the original, unrotated list, and with my methods, it will refer to the updated, rotatedlist/deque.

使用您的方法,c将继续引用原始的、未旋转的列表,而使用我的方法,它将引用更新的、旋转的列表/双端队列。