Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.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=[1,2,3] 如果条件满足 如果条件==True, 我想将列表的顺序更改为a=[1,3,2] 在python中最有效的方法是什么?尝试以下方法。这就像交换 a[0],a[1]=a[1],a[0] 针对您的具体情况 a[1],a[2]=a[2],a[1]试试这个: a=[1,2,3] if true: temp = a[1] a[1] = a[2] a[2] = temp 输出将为: Given List: ['a', 'b', 'c'] Inter

我有一张单子
a=[1,2,3]

如果条件满足
如果条件==True
, 我想将列表的顺序更改为
a=[1,3,2]


在python中最有效的方法是什么?

尝试以下方法。这就像交换
a[0],a[1]=a[1],a[0]

针对您的具体情况
a[1],a[2]=a[2],a[1]

试试这个:

a=[1,2,3]

if true:
    temp = a[1]
    a[1] = a[2]
    a[2] = temp
输出将为:

Given List: ['a', 'b', 'c']
Interchanged List: ['c', 'b', 'a']
       
Given List: ['a', 'b', 'c']
Interchanged List: ['c', 'b', 'a']