我是Python的新手。在Codingbat上练习使用列表时,我意识到有一些行为我不了解关于列表和可变变量的行为。下面的例子是从一些编码问题中衍生出来的,用来构建我的问题
在getManipulatedNewList()中,newnums被销毁,因为它超出了范围(这是正确的?),所以这就是为什么bobo第一次没有得到任何结果
我现在假设确保获得列表的实际副本的唯一方法是在函数外部创建它,所以深度复制必须发生在操作列表的函数外部,在使用新列表的同一范围内。对吗
然后在下面的最后一个函数中传递什么(whatisthisdoying()——显然,我正在创建一个包含参数“nums”的第一个和最后一个元素的新列表,然后立即返回。Bobo被成功地分配给新的列表(否则arr[0]=999也会更改Bobo中的第一个值)
为什么这样做有效,但是getManipulatedNewList()会破坏newnums
有没有什么方法可以像返回匿名列表一样传递newnums,这样它就不会被销毁
(或者我在这里误解了什么,请:)
import copy
def getManipulatedNewList(nums):
# Create new list
newnums = copy.deepcopy(nums)
# For example only; assume many, more complex list manipulations
# occur here
newnums = newnums.reverse()
# Return the newly-created list reference (doesn't work.)
return newnums
def manipulateList(nums):
# For example only; assume many, more complex list modifs
# occur here
nums = nums.reverse()
# Nothing to return
def whatIsThisDoing(nums):
# This actually returns something!
# Why, though? It's creating the new list in this function too.
return [nums[0], nums[-1]]
if __name__ == '__main__':
arr = [1,2,3]
print(arr)
print("---")
bobo = getManipulatedNewList(arr)
print(arr) # Shouldn't be touched, as expected
print(bobo) # newnums was destroyed so bobo is None
print("---")
# Is this the only good solution to working with mutable vars?
bobo = copy.deepcopy(arr)
manipulateList(bobo)
print(bobo)
# Why does this work?
bobo = whatIsThisDoing(arr)
print(bobo)
print("---")
arr[0] = 999
print(bobo) # bobo[0] isn't changed, so it's not referencing arr[0]
不,没有的原因是因为它是从
reverse
返回的;这种方法是可行的。这个问题与范围无关,你们其余的误解都源于此相关问题 更多 >
编程相关推荐