Python列表+列表vs. list.append() [英] Python list + list vs. list.append()

查看:746
本文介绍了Python列表+列表vs. list.append()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我花了大约20分钟试图弄清楚为什么 这按预期工作:

Today I spent about 20 minutes trying to figure out why this worked as expected:

users_stories_dict[a] = s + [b] 

,但这将具有None值:

users_stories_dict[a] = s.append(b)

任何人都知道为什么append函数不返回新列表吗?我正在寻找做出此决定的明智原因;现在看来,这对我来说就像是Python新手.

Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this decision was made; it looks like a Python novice gotcha to me right now.

推荐答案

append实际是通过修改列表来完成的,所以所有的魔术都是副作用.因此,append返回的结果为None.换句话说,一个人想要的是:

append works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by append is None. In other words, what one wants is:

s.append(b)

然后:

users_stories_dict[a] = s

但是,您已经知道了很多.至于为什么这样做,虽然我真的不知道,但我的猜测是它可能与0(或false)退出值有关,该退出值指示操作正常进行,并通过返回None对于作用是就地修改其参数的函数,您报告修改成功.

But, you've already figured that much out. As to why it was done this way, while I don't really know, my guess is that it might have something to do with a 0 (or false) exit value indicating that an operation proceeded normally, and by returning None for functions whose role is to modify their arguments in-place you report that the modification succeeded.

但是我同意,如果它返回修改后的列表会很好.至少,Python的行为在所有此类函数中都是一致的.

But I agree that it would be nice if it returned the modified list back. At least, Python's behavior is consistent across all such functions.

这篇关于Python列表+列表vs. list.append()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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