请解释该程序的输出 [英] Please explain the output of the program

查看:60
本文介绍了请解释该程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def extendList(val, list=[]):
      list.append(val)
      return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print(list1)
print(list2)
print(list3)





什么我试过了:



程序的输出是



What I have tried:

the output of the program is

list1 -- [10,'a']
list2 -- [123]
list3 -- [10,'a']





list1的输出中有'a'如何



How does list1 have 'a' in its output

推荐答案

引用:

list1如何在其输出中包含'a'

How does list1 have 'a' in its output



必须这样做如何在Python内部处理指针。

当您在变量中存储列表时,列表不会被复制,而是指向实际列表的指针存储在变量中,它既有内存效率又快速。

对我来说,直观的是 list = [] 第二次不创建新列表,但重用与第一次相同时间。

查看文档以获取有关列表和指针的详细信息。

使用调试器查看确切的内容。

- ---

你的代码没有你想象的那样,或者你不明白为什么!



几乎是通用的解决方案:一步一步地在调试器上运行代码,检查变量。

调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

调试器中没有魔法,它不知道你的代码应该做什么,它没有找到错误,它只是通过向你展示帮助你到底是怎么回事。当代码没有达到预期的效果时,你就接近了一个错误。

要查看你的代码在做什么:只需设置断点并查看代码是否正常运行,调试器允许你执行第1行第1行,并在执行时检查变量。

调试器 - 维基百科,免费的百科全书 [ ^ ]

27.3。 pdb - Python调试器 - Python 3.6.1文档 [ ^ ]

使用Python进行调试Python征服宇宙 [ ^ ]

pdb - 交互式调试器 - 本周的Python模块 [ ^ ]



调试器只是向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。


This have to do with how Python internally deals with pointers.
When you store a list in a variable, the list is not copied, instead a pointer to actual list is stored in variable, it is both memory efficient and fast.
What is counter intuitive to me is that list=[] do not create a new list the second time, but reuse the same as first time.
Have look at documentation for details about lists and pointers.
Use the debugger to see exactly what is going on.
-----
Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.
Debugger - Wikipedia, the free encyclopedia[^]
27.3. pdb — The Python Debugger — Python 3.6.1 documentation[^]
Debugging in Python | Python Conquers The Universe[^]
pdb – Interactive Debugger - Python Module of the Week[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.


重要警告:的段落 4。更多控制流工具 - Python 3.4.9文档 [ ^ ]


这篇关于请解释该程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆