gpt4 book ai didi

python - 了解可变变量在不同范围内的行为方式

转载 作者:行者123 更新时间:2023-11-30 22:25:04 26 4
gpt4 key购买 nike

这里是 Python 新手。在 Codingbat 上练习使用列表时,我意识到有些关于列表的行为以及可变变量的行为方式我不理解。下面的示例源自一些 Codingbat 问题来框架我的问题...

  1. 在 getManipulatedNewList() 中,newnums 被销毁,因为它超出了范围(这是正确的吗?),所以这就是 bobo 第一次得到 None 的原因。

  2. 我现在假设确保获得列表的实际副本的唯一方法是在函数外部创建它 - 因此深度复制必须发生在操作列表的函数外部列表,在将使用新列表的同一范围内。对吗?

  3. 那么下面最后一个函数中传递的是什么(whatIsThisDoing())——我显然是用参数“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]

最佳答案

没有。您得到 None 的原因是因为这是从 reverse 返回的内容;该方法有效。这个问题与范围无关,你的其余误解都源于此。

关于python - 了解可变变量在不同范围内的行为方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47642737/

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