python - 解释打印 test_list

标签 python python-2.7

你能给我详细解释一下节目的后半部分吗?我知道 input_list[0] = 10 是一个变量,其范围为 1 - 10,但是列表 [1, 2, 3, 4、5、6、7、8、9、10][10、2、3、4、5、6、7、8、9] [10, 5, 5] 来自哪里?

def list_changer(input_list):
    input_list[0] = 10

    input_list = range(1, 10)
    print(input_list)
    input_list[0] = 10
    print(input_list)

>>> test_list = [5, 5, 5]
>>> list_changer(test_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print test_list
[10, 5, 5]

预先感谢您提供的所有帮助。

最佳答案

使用 id 尝试此操作

def list_changer(input_list):
    input_list[0] = 10
    print id(input_list)
    input_list = range(1, 10)
    print(input_list)
    input_list[0] = 10
    print(input_list)


>>>test_list = [5, 5, 5]
>>>print id(test_list)
>>>list_changer(test_list)
>>>print test_list

#output

139794448752512
139794448752512
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 5, 5]

从中我们可以看出idtest_listinput_list 相同在 1st函数行。即两者都引用 [5,5,5] .所以更改为test_listinput_list (第一行)将影响引用它的所有变量。 1st行是 [5,5,5] 发生变化的地方.

然后input_list = range(1, 10) .这次input_list正在引用range(1, 10) .仍然[10,5,5]通过变量 test_list 引用.

希望这有帮助

关于python - 解释打印 test_list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29463474/

相关文章:

python - 如何生成具有给定限制和平均值的随机数?

python-2.7 - 在 python 中使用 super 和 class 方法

python - 你如何从 BeautifulSoup 结果中获得第三个链接

python - 处理多个列表

Python 单行 while 循环

python - 如何在 3d numpy 数组中查找 2d 数组的行

python - 当存在 unicode 值时计算 NaN

python - 计算一次,缓存结果,并从缓存中无限返回的函数(Python)

python - 如何从 Python 中的补丁中恢复 3D 图像?

Python3 : Enter regex pattern from command line