[英]Why this parameter list doesn't change in Python?
I created a function f which uses a 2-dimension list as parameter, but after this function the list does not change at all.我创建了一个 function f ,它使用二维列表作为参数,但是在此 function 之后列表根本没有改变。 As the code below:
如下代码:
def f(t: [[int]]):
for eachrow in t:
eachrow = eachrow[1:]
eachrow.append(0)
A = [[2, 10, 0], [3, 1, 2], [3, 2, 1]]
f(A)
print(A) # -> [[2, 10, 0], [3, 1, 2], [3, 2, 1]]
Assigning to eachrow
in eachrow = eachrow[1:]
overwrites it.分配给
eachrow
eachrow = eachrow[1:]
中的每一行会覆盖它。 So to remove the first element, you could use del
instead, or row.pop
or slice assignment .所以要删除第一个元素,你可以使用
del
代替,或者row.pop
或slice assignment 。
def f(t):
for row in t:
del row[0] # OR row.pop(0) OR row[:] = row[1:]
row.append(0)
A = [[2, 10, 0], [3, 1, 2], [3, 2, 1]]
f(A)
print(A) # -> [[10, 0, 0], [1, 2, 0], [2, 1, 0]]
If you print out the results of your changes to eachrow
, you'll see that you ARE updating the eachrow
variable, but that doesn't affet the original t
variable.如果您打印出对
eachrow
的更改结果,您会看到您正在更新eachrow
变量,但这不会影响原始t
变量。
def f(t):
for eachrow in t:
eachrow = eachrow[1:]
eachrow.append(0)
print(eachrow)
>>> f(A)
[10, 0, 0]
[1, 2, 0]
[2, 1, 0]
If you want to affect the array itself, you should modify the array like so:如果你想影响数组本身,你应该像这样修改数组:
def f(t):
for row_number in range(len(t)):
t[row_number] = t[row_number][1:]
t[row_number].append(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.