在列表中移动项目? [英] Move an item inside a list?

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

问题描述

在Python中,如何将项目移动到列表中的确定索引?

In Python, how do I move an item to a definite index in a list?

推荐答案

使用列表的insert方法:

l = list(...)
l.insert(index, item)

或者,您可以使用切片符号:

Alternatively, you can use a slice notation:

l[index:index] = [item]

如果要将列表中已有的项目移动到指定位置,则必须将其删除并将其插入新位置:

If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:

l.insert(newindex, l.pop(oldindex))

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

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