为什么附加到列表会在 Python 中引发 NoneType 错误? [英] Why does appending to a list raise a NoneType error in Python?

查看:21
本文介绍了为什么附加到列表会在 Python 中引发 NoneType 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

text="""col1 col2 col3
a 1 $
b 2 @
c 3 &
"""
mList = []
for line in text.splitlines():
    for item in line.split(" "):
        mList = mList.append(item)

这会引发错误,'NoneType' 对象没有属性 'append'.我尝试了其他方法来创建列表并执行此操作,但我得到的最好的方法是将列表变为 None.这是怎么回事?

This raises an error, 'NoneType' object has no attribute 'append'. I've tried other ways of creating the list and doing this, but the best I get is the list turned to None. What's going on here?

推荐答案

list.append() 是一个就地方法,它不返回任何内容(因此默认情况下它返回 None ,因为所有函数 calls 必须返回一些值,如果某个函数没有显式返回任何值,则调用返回`None).

list.append() is an in-place method, it does not return anything ( and hence by default it returns None , as all function calls must return some value, and if some function does not explicitly return anything, the call returns `None).

因此,当您将其分配回 mList 时,它将变为 None 并且在您执行的下一次迭代中 - mList.append()> ,它会出错,因为 mListNone.

Hence, when you assign it back to mList, it becomes None and in the next iteration when you do - mList.append() , it errors out as mList is None.

你应该试试——

mList.append(item)

<小时>

或者你可以简单地在列表理解中做你想做的事情 -


Or you can simply do what you are trying to do in a list comprehension -

mList = [item for line in text.splitlines() for item in line.split(" ")]

这篇关于为什么附加到列表会在 Python 中引发 NoneType 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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