Python 3:为什么.append()在方案中而不是第二种?
并且正在努力理解这些代码的这些位置:
def append_size(lst):
lst.append(len(lst))
return lst
VS
def append_size(lst):
return lst.append(len(lst))
两个功能均使用print(append_size([23,42,108])调用
我正在通过Codecademy学习Python 3 , 作品(印刷[23,42,108,3])和第二个返回“无”?
I'm learning Python 3 through Codecademy and am struggling to understand the difference between these bits of code:
def append_size(lst):
lst.append(len(lst))
return lst
vs
def append_size(lst):
return lst.append(len(lst))
Both functions are called with print(append_size([23, 42, 108])
Why does the first work (prints [23, 42, 108, 3]) and the second returns 'None'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发生这种情况是因为当您
append()
列表中的某些东西没有返回。它只需将项目附加到列表中,然后返回none
,如果您打印出来。例如:在这种情况下,
4
将附加到称为l
的列表中。附加的简单任务是将项目添加到最后的列表中。因此,当您进行打印(L.Append(4))
时,它说none
。但是,如果您尝试:
在此处打印列表的 value
l
在4
之后。This happens because when you
append()
something to a list nothing is returned. It simply appends the item to the list and returnsNone
if you print it. Eg:In this case,
4
is getting appended to a list calledl
. The simple task of append is adding the item to the list at the end. Hence, when you doprint(l.append(4))
it saysNone
.But if you try:
Here it prints the value of the list
l
after4
is appended.好的,因此
附加
函数用于将项目添加到现有列表中。假设我有一个列表
a = [1,2,3]
,我想将4
添加到列表中。我会做A.append(4)
,并将获得[1,2,3,4]
的所需输出。在第一个
append_size
函数中,代码首先将项目附加到原始列表中,然后返回列表,这就是为什么您获得的列表输出的原因[23,42,108,3]
。但是在第二个功能中,代码返回lst.append
,而没有任何列表。因为附加
函数始终具有无值,所以它又返回了输出。Okay so the
append
function is used to add an item to an existing list.Suppose I have a list
a = [1,2,3]
and I want to add4
to the list. I'll doa.append(4)
and would get the desired output of[1,2,3,4]
.In the first
append_size
function the code firstly appends an item to the original list and then returns the list that's why you get a list output of[23, 42, 108, 3]
. But in the second function the code returnslst.append
and not any list. Because theappend
function always has the value None, it returned None as the output.