8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

为什么这些列表方法(附加、排序、扩展、删除、清除、反转)返回 None 而不是结果列表?

alxbxbx 2月前

54 0

我注意到,许多修改列表内容的列表操作将返回 None,而不是返回列表本身。示例:>>> mylist = ['a', 'b', 'c']>>> empt...

我注意到,许多修改列表内容的列表操作都会返回 None ,而不是返回列表本身。示例:

>>> mylist = ['a', 'b', 'c']
>>> empty = mylist.clear()
>>> restored = mylist.extend(range(3))
>>> backwards = mylist.reverse()
>>> with_four = mylist.append(4)
>>> in_order = mylist.sort()
>>> without_one = mylist.remove(1)
>>> mylist
[0, 2, 4]
>>> [empty, restored, backwards, with_four, in_order, without_one]
[None, None, None, None, None, None]

这个决定背后的想法是怎样的?

在我看来,这似乎是一种阻碍,因为它阻止了列表处理的“链接”(例如 mylist.reverse().append('a string')[:someLimit] )。我想可能是“当权者”认为列表理解是一种更好的范例(一种有效的观点),因此不想鼓励其他方法 - 但阻止直观的方法似乎有悖常理,即使存在更好的替代方案。


This question is specifically about Python's design decision to return None from mutating list methods like .append . However, novices often write incorrect code that expects .append (in particular) to return the same list that was just modified. Please do close such questions as a duplicate of this one, however. "The code did the wrong thing because the result was None rather than the list" is something that the OP in these cases should have discovered independently via debugging; creating a proper MRE leaves behind a question like this one - therefore, it can be considered a duplicate.

See 如何将重复计算的结果收集到列表、字典等中(或复制每个元素均经过修改的列表)? for the simple question of " how do I append to a list repeatedly?" (or debugging questions that boil down to that problem). This is a new canonical that has been specifically prepared to address the topic with the perspective that beginners lack.

要获取列表的修改版本,请参阅:

The same issue applies to some methods of other built-in data types, e.g. set.discard (see 如何使用列表推导从列表内的集合中删除特定元素 ) and dict.update (see 为什么 python dict.update() 不返回对象? ).

The same reasoning applies to designing your own APIs. See 让就地操作返回对象是不是一个坏主意? .

帖子版权声明 1、本帖标题:为什么这些列表方法(附加、排序、扩展、删除、清除、反转)返回 None 而不是结果列表?
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由alxbxbx在本站《algorithm》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 有人可能会说,签名本身清楚地表明该函数会改变列表而不是返回一个新的列表:如果该函数返回一个列表,那么它的行为就不会那么明显了。

返回
作者最近主题: