Python 列表 + 列表 与 列表.append()

6 投票
2 回答
11947 浏览
提问于 2025-04-16 15:19

今天我花了大约20分钟在想,为什么下面这个代码能正常工作:

users_stories_dict[a] = s + [b] 

但是这个代码却会得到一个None的值:

users_stories_dict[a] = s.append(b)

有没有人知道为什么append这个函数不返回新的列表?我想知道这个决定背后有没有什么合理的原因;现在看来,这就像是让Python新手困惑的一个小陷阱。

2 个回答

9

append() 方法返回 None,因为它是直接在原来的列表上添加一个元素,而 + 操作符则是把两个列表合并在一起,并返回合并后的新列表。

比如:

a = [1,2,3,4,5]
b = [6,7,8,9,0]

print a+b         # returns a list made by concatenating the lists a and b
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print a.append(b) # Adds the list b as element at the end of the list a and returns None
>>> None

print a           # the list a was modified during the last append call and has the list b as last element
>>> [1, 2, 3, 4, 5, [6, 7, 8, 9, 0]]

所以你可以看到,最简单的方法就是把两个列表直接加在一起。即使你用 append() 把列表 b 加到 a 上,你也不会得到想要的结果,还需要额外的操作。

12

append这个方法是通过直接修改一个列表来工作的,所以它的“魔法”在于它的副作用。也就是说,append返回的结果是None。换句话说,你想要做的是:

s.append(b)

然后再:

users_stories_dict[a] = s

不过,你已经明白这一点了。至于为什么要这样设计,我也不太清楚,但我猜这可能和一个0(或者false)的返回值有关,表示操作正常进行。而对于那些目的是在原地修改参数的函数,返回None可以表明修改成功。

不过我同意,如果它能返回修改后的列表就好了。至少,Python在所有这样的函数中的行为是一致的。

撰写回答