Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.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_List_Function - Fatal编程技术网

Python 函数,用于更改列表中两个元素的位置

Python 函数,用于更改列表中两个元素的位置,python,list,function,Python,List,Function,我必须编写一个函数,如果我编写此函数,该函数将起作用: s = ["John", "Bertha", "Janna", "Daniel", "Emma"] change(s,2,4) print(s) ["John", "Bertha", "Emma", "Daniel", "Janna"] 我基本上需要定义一个函数来改变列表中2个元素的位置,其中a,b是它们的索引 我试过这样做,但似乎找不到好的解决办法: def change(s,a,b): a,b = s.index(a), s.

我必须编写一个函数,如果我编写此函数,该函数将起作用:

s = ["John", "Bertha", "Janna", "Daniel", "Emma"]
change(s,2,4)
print(s)
["John", "Bertha", "Emma", "Daniel", "Janna"]
我基本上需要定义一个函数来改变列表中2个元素的位置,其中a,b是它们的索引

我试过这样做,但似乎找不到好的解决办法:

def change(s,a,b):
    a,b = s.index(a), s.index(b)
    s[b], s[a] = s[a], s[b]
这显然不起作用,我不知道如何改变2个元素的位置,其中a,b是它们的索引,我知道如何切换2个项目,但不知道如何使用函数来完成。。如何处理这个问题呢?

a和b是需要切换的项目的索引。如果您已经知道它们在哪里,则可以删除对list.index的调用:

如果你已经有了索引,为什么要调用索引?!试试打印A,b看看发生了什么。
>>> s = ["John", "Bertha", "Janna", "Daniel", "Emma"]
>>> def change(s, a, b):
...     s[b], s[a] = s[a], s[b]
...
>>> change(s, 2, 4)
>>> s
['John', 'Bertha', 'Emma', 'Daniel', 'Janna']
>>>