Python 函数对列表进行就地更改
我想更改列表中两个列表的位置。 像这样:Python 函数对列表进行就地更改,python,Python,我想更改列表中两个列表的位置。 像这样: A = [[2,3,4], [5,-3,6]] swap(A[0], A[1]) print(A) #[[5,-3,6],[2,3,4]] 这不起作用(为什么?) 虽然这样做有效(为什么?) Python按值传递引用。在第一个函数中,传入对row1和row2的引用,切换这些引用,但这不会更改外部的列表 如果要在这样的列表中交换元素,应传入该列表,以便修改列表中的引用: def swap(mylist): mylist[0], mylist[1]
A = [[2,3,4], [5,-3,6]]
swap(A[0], A[1])
print(A)
#[[5,-3,6],[2,3,4]]
这不起作用(为什么?)
虽然这样做有效(为什么?)
Python按值传递引用。在第一个函数中,传入对
row1
和row2
的引用,切换这些引用,但这不会更改外部的列表
如果要在这样的列表中交换元素,应传入该列表,以便修改列表中的引用:
def swap(mylist):
mylist[0], mylist[1] = mylist[1], mylist[0]
# This works for a list of ints
this_list = [1, 2]
swap(this_list)
this_list
# [2, 1]
# Or for a list of lists (Note that the lengths aren't the same)
that_list = [[1, 2, 3], [4, 5]]
swap(that_list)
that_list
# [[4, 5], [1, 2, 3]]
(同样值得注意的是,您可以使用python执行多个赋值,因此不需要使用
temp
变量。)谢谢!如果你有两个列表,而不是一个,长度未知,会是什么样子?我猜你必须执行for循环?在Python社区中,你可能会听到“参数通过赋值传递”,甚至“通过共享调用”或“通过对象共享调用”()。@Jmei如果我理解正确,它应该以同样的方式工作。查看我的编辑,看看你是否还有问题谢谢!但输入仍然是一个列表?一个列表中只有两个列表。如果函数以两个单独的列表作为输入,即函数有两个输入参数,而不是一个。@Jmei如果您想切换两个列表的元素,那么您可以像在上一个示例中一样进行切换。正如我在回答中提到的那样,我唯一要注意的是多重赋值的问题。(在python中交换不需要temp
)。
def swap(row1,row2):
for i in range(0,len(row2)):
temp = row2[i]
row2[i] = row1[i]
row1[i] = temp
def swap(mylist):
mylist[0], mylist[1] = mylist[1], mylist[0]
# This works for a list of ints
this_list = [1, 2]
swap(this_list)
this_list
# [2, 1]
# Or for a list of lists (Note that the lengths aren't the same)
that_list = [[1, 2, 3], [4, 5]]
swap(that_list)
that_list
# [[4, 5], [1, 2, 3]]