Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何获取位置而不是交换列表编号_Python - Fatal编程技术网

在python中,如何获取位置而不是交换列表编号

在python中,如何获取位置而不是交换列表编号,python,Python,我有这样的数字: a = [3, 4, 5, 7, 2, 8, 6, 9, 1] 我想把这个数字放在一个类似[2,3,4,5,7,8,6,9,1]的列表中。您可以使用remove删除列表中某个元素的第一个实例,并使用insert在任意位置插入某个元素: a.remove(2) a.insert(0, 2) # 0 means insert at the first position in the list 但是,如果使用的是remove,请记住,如果要删除的元素不在列表中,则代码将引发V

我有这样的数字:

a = [3, 4, 5, 7, 2, 8, 6, 9, 1]
我想把这个数字放在一个类似[2,3,4,5,7,8,6,9,1]的列表中。

您可以使用remove删除列表中某个元素的第一个实例,并使用insert在任意位置插入某个元素:

a.remove(2)
a.insert(0, 2)   # 0 means insert at the first position in the list
但是,如果使用的是remove,请记住,如果要删除的元素不在列表中,则代码将引发ValueError。因此,如果不确定某个元素是否在列表中,则应在使用“删除”之前进行检查:


我会使用列表索引

> [a[4]]+a[:4]+a[4+1:]
[2, 3, 4, 5, 7, 8, 6, 9, 1]
一种方法是使用list.insert和list.pop

这将删除位置4中的项目并将其移动到位置0。请记住,Python中的索引从0开始

Python中可用的列表方法的详细信息。

除了@jpp之外,如果希望动态获取列表中第2号的索引值,还可以执行以下操作:

a.insert(0, a.pop(a.index(2)))
a、 index2-将在列表中找到数字2第一次出现的索引,在本例中返回4

a、 pop4-将从列表中删除第4个值并返回它。此返回2


a、 insert0,2-将值2插入索引0处的列表。

是否有一般情况?这背后的逻辑是什么?我开始学习,我试图让这一切发生,但我做不到。所以这是我@olivier melançontanks的一般情况,我需要@jpp的评论和澄清
a = [3, 4, 5, 7, 2, 8, 6, 9, 1]

a.insert(0, a.pop(4))

# [2, 3, 4, 5, 7, 8, 6, 9, 1]
a.insert(0, a.pop(a.index(2)))