gpt4 book ai didi

python - 为什么这个参数列表在 Python 中没有改变?

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:04 25 4
gpt4 key购买 nike

我创建了一个函数 f,它使用一个二维列表作为参数,但是在这个函数之后列表根本没有改变。如以下代码:

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]]

最佳答案

分配给 eachrow = eachrow[1:] 中的 eachrow 会覆盖它。因此,要删除第一个元素,您可以改用 del,或者 row.popslice 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]]

关于python - 为什么这个参数列表在 Python 中没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58868615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com