我有一个带有返回值的函数。
每个调用都分配给一个不同的变量。
为什么第二个函数调用后第一个变量array_squares
得到新值?
变量不应该相关。
代码:
array1=[]
for i in range(1,11):
array1.append(i)
print(array1)
#calculate square of each number
def calc_square(array, types):
for x in range(len(array)):
if(types=="square"):
array[x]=1
if(types=="cube"):
array[x]=2
return array
print("original array", array1)
array_squares=calc_square(array1, "square")
print("after first call", array_squares)
array_cube=calc_square(array1, "cube")
print("after function sqaure: ", array_squares)
print("after function cube ", array_cube)
这将返回:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
original array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after first call: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
after function square: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
after function cube: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
答案 0 :(得分:0)
您必须将数组的副本提供给函数, 因为函数会更改您输入的数组 函数并返回它。
您可以通过调用import copy
copy.copy(<obj>)
库进行此操作
您改进的代码:
import copy
array1=[]
for i in range(1,11):
array1.append(i)
print(array1)
#calculate square of each number
def calc_square(array, types):
for x in range(len(array)):
if(types=="square"):
array[x]=1
if(types=="cube"):
array[x]=2
return array
print("original array", array1)
array_squares=calc_square(copy.copy(array1), "square")
print("after first call", array_squares)
array_cube=calc_square(copy.copy(array1), "cube")
print("after function sqaure: ", array_squares)
print("after function cube ", array_cube)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
original array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after first call [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
after function sqaure: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
after function cube [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]