在python中将.extend应用于列表的方法之间的差异

2024-03-28 22:15:29 发布

您现在位置: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'])

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


Tags: 方法fromimportenglish原因corpus差异subject
1条回答
网友
1楼 · 发布于 2024-03-28 22:15:29

TL;博士

list.extend()扩展列表,但返回无。

这是使用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中list extend函数的实现:https://github.com/python/cpython/blob/master/Objects/listobject.c#L872

我们看到函数返回Py_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'>

相关问题 更多 >