Python 3:为什么.append()在方案中而不是第二种?

发布于 2025-01-24 19:40:20 字数 322 浏览 2 评论 0原文

并且正在努力理解这些代码的这些位置:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵强ㄟ 2025-01-31 19:40:20

发生这种情况是因为当您append()列表中的某些东西没有返回。它只需将项目附加到列表中,然后返回none,如果您打印出来。例如:

l = [1,2,3]
print(l.append(4))
None

在这种情况下,4将附加到称为l的列表中。附加的简单任务是将项目添加到最后的列表中。因此,当您进行打印(L.Append(4))时,它说none

但是,如果您尝试:

l = [1,2,3]
l.append(4)
print(l)
[1, 2, 3, 4]

在此处打印列表的 value l4之后。

This happens because when you append() something to a list nothing is returned. It simply appends the item to the list and returns None if you print it. Eg:

l = [1,2,3]
print(l.append(4))
None

In this case, 4 is getting appended to a list called l. The simple task of append is adding the item to the list at the end. Hence, when you do print(l.append(4)) it says None.

But if you try:

l = [1,2,3]
l.append(4)
print(l)
[1, 2, 3, 4]

Here it prints the value of the list l after 4 is appended.

心安伴我暖 2025-01-31 19:40:20

好的,因此附加函数用于将项目添加到现有列表中。

假设我有一个列表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 add 4 to the list. I'll do a.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 returns lst.append and not any list. Because the append function always has the value None, it returned None as the output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文