python 中将 .extend 应用于列表的方式之间的区别

Difference between the ways of applying .extend to a list in python

我不是 python 方面的专家,我希望一些专家帮助我理解我在下面尝试的两种方式的输出差异

from nltk.corpus import stopwords
stop_words = stopwords.words('english')
stop_words.extend(['from', 'subject'])
from nltk.corpus import stopwords
stop_words = stopwords.words('english').extend(['from', 'subject'])

我认为第二种方法与第一种相同,但我错了。我不明白这种行为改变背后的原因。

TL;DR

list.extend() 扩展列表但 returns 一个 None.

这是使用 list.extend():

的正确方法
>>> from nltk.corpus import stopwords
>>> stop_words = stopwords.words('english')
>>> stop_words.extend(['from', 'subject'])

让我们看看 stop_words 类型是什么:

>>> type(stop_words)
<class 'list'>

如果我们看https://docs.python.org/3/tutorial/datastructures.html

list.extend(iterable)

Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

CPython中列表扩展函数的实现如下:https://github.com/python/cpython/blob/master/Objects/listobject.c#L872

我们看到函数returnsPy_RETURN_NONE;

在Python用法中进行说明:

# We have a list `x`
>>> x = [1,2,3]
# We extend list `x` and assigns the output of `extend()` to `y`
>>> y = x.extend([4,5])
# We see that `x` is extended but `y` is assigned None.
>>> x
[1, 2, 3, 4, 5]
>>> y
>>> type(y)
<class 'NoneType'>

# But if you extend `x` and then assigns output of `extend()` to `x`
# It assigns None to the `x`

>>> x = [1,2,3]
>>> x = x.extend([4,5])
>>> x
>>> type(x)
<class 'NoneType'>