python 按值传递与按引用传递 [英] python pass-by-value vs. pass-by-reference

查看:35
本文介绍了python 按值传递与按引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我理解python的传递引用处理......为什么列表的传递引用与列表元素的传递引用之间存在差异,特别是如果两者都是我所理解的对象:

I thought I understood python's pass-by-reference processing... Why is there a difference between pass-by-reference for lists vs. that for list elements, specially if both are objects as far as I understand it:

 dataBloc = [ ['123'] , ['345'] ]

 print dataBloc

 def func( b ):
     print ( 'Row-by-Row Before' , b )
     for row in b:
         row = [ float(x) for x in row ]
     print ( 'Row-by-Row After' , b )

     print ( 'Element-by-Element Before' , b )
     for row in b:
         for i in range(len(row)):
             row[i] = float(row[i])
     print ( 'Element-by-Element After' , b )

     return b

 print func(dataBloc)

 [['123'], ['345']]
 ('Row-by-Row Before', [['123'], ['345']])
 ('Row-by-Row After', [['123'], ['345']])
 ('Element-by-Element Before', [['123'], ['345']])
 ('Element-by-Element After', [[123.0], [345.0]])
 [[123.0], [345.0]]

谢谢.

推荐答案

首先,这个问题与值传递或引用传递无关,因为你没有做任何传递,你'重新简单地改变函数内的值.

Firstly, this question has nothing to do with either pass-by-value or pass-by-reference, because you're not doing any passing, you're simply mutating values within a function.

其次,没有这样的区别.不同之处在于您的代码:您正在做不同的事情.在第一个循环中,您将列表中的每个元素分配给名称row".然后,您重新分配名称行"以指向其他内容.之前在 'row' 中的实际值没有改变,所以原始列表本身当然没有改变,因为你实际上并没有改变内容.

Secondly, there is no such difference. The difference is in your code: you are doing different things. In the first loop, you assign each element in the list to the name 'row'. Then, you reassign the name 'row' to point to something else. The actual value that was previously in 'row' is unchanged, so of course the original list is itself unchanged, since you didn't actually change the contents.

在第二个中,在每一行中,您通过索引专门改变每个元素的内容.因此,列表已更改.

In the second, inside each row you specifically mutate the contents of each element via its index. So, the list is changed.

这篇关于python 按值传递与按引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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