I created a function f which uses a 2-dimension list as parameter, but after this function the list does not change at all. 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. So to remove the first element, you could use del
instead, or row.pop
or 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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.