Python 简单交换函数 [英] Python Simple Swap Function

查看:40
本文介绍了Python 简单交换函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试学习 python 时遇到了这个问题.考虑以下函数:

I came across this problem when attempting to learn python. Consider the following function:

def swap0(s1, s2):
    assert type(s1) == list and type(s2) == list
    tmp = s1[:]
    s1 = s2[:]
    s2 = tmp
return

s1 = [1]
s2 = [2]
swap0(s1, s2)
print s1, s2

s1 和 s2 会打印什么?

What will s1 and s2 print?

运行问题后,发现print语句会打印1 2.看来s1和s2的值并没有从swap0函数中改变.我能想到的唯一解释是因为这条线.

After running the problem, I found that the print statement will print 1 2. It seems that the value of s1 and s2 did not change from the swap0 function. The only explanation that I could think of was because of the line.

tmp = s1[:]

因为 s1[:] 是一个副本,所以在函数调用中 s1 的值不会改变是有道理的.但是因为swap0的参数是(s1, s2),所以不知道做tmp = s1[:]后是否.任何时候都可以

Since s1[:] is a copy, this makes sense that the value of s1 will not change in the function call. However because the parameter of swap0 is (s1, s2), I am not sure if after doing tmp = s1[:]. Anytime I do

s1 = something...

它将是对 s1 副本的引用,而不是 s1 本身.有人可以提供更好的解释吗?谢谢.

it will be a reference to the copy of s1, instead of s1 itself. Can someone offer a better explanation? Thanks.

推荐答案

这是因为它在 swap0 中为 s1s2 分配了新值> 功能.这些赋值不会在函数外传播.如果您只是将函数体复制并粘贴到函数调用的位置,您就会发现它是有效的.

It's because it assigns new values to s1 and s2 inside the swap0 function. These assignments do not propagate outside the function. You'll see that it works if you just copy and paste the function body in the place of the function call.

您可以通过修改参数引用的对象而不是参数本身来解决此问题:

You can work around this by modifying the objects referenced by the arguments, rather than the arguments themselves:

def swap0(s1, s2):
    assert type(s1) == list and type(s2) == list
    tmp = s1[:]
    s1[:] = s2
    s2[:] = tmp

然而,在 Python 中进行交换的更简单更好的方法很简单:

However, the easier and better way to do a swap in Python is simply:

s1, s2 = s2, s1

这也只会交换对列表的特定引用,而不是列表内容本身.

This, too, will only swap those particular references to the lists, but not the list contents themselves.

这篇关于Python 简单交换函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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