移动值,但在Python列表中保留顺序 [英] Moving values but preserving order in a Python list

查看:98
本文介绍了移动值,但在Python列表中保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表

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

并希望移动"其值,以便将其更改为

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

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

以及下一步

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

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

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

或者比这更短或更友善的方式

Or is there a shorter or nicer way than

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

推荐答案

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

但是,这很昂贵,因为它必须移动整个列表的内容,即O(n).更好的选择是使用 collections.deque (如果在您的Python版本,它允许在大约O(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.deque if it is available in your version of Python, which allow objects to be inserted and removed from either end in approximately O(1) time:

>>> 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])

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

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:

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

在您的方法中,c将继续引用原始的未旋转列表,而在我的方法中,它将引用更新后的旋转列表/双端队列.

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

这篇关于移动值,但在Python列表中保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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