Python:在for循环中列出append() [英] Python: List append() in for loop

查看:836
本文介绍了Python:在for循环中列出append()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,试图用一个循环对列表做最基本的附加函数:
不知道我在这里丢失了什么:

a = a.append(i)
a
a = []
/ pre>

返回:
'NoneType'对象没有属性'append'

list.append 函数没有返回任何值,只是添加了值到您用来调用该方法的列表。

在第一个循环中,您将分配 None (因为附加)到 a ,然后在第二轮尝试调用 a.append ,as a是None 它会引发你正在寻找的异常



你只需要把它改成:

  a = [] 
在范围内(5):
a.append(i)
a#包含新项目的列表。


In Python, trying to do the most basic append function to a list with a loop: Not sure what i am missing here:

a=[]
for i in range(5):    
    a=a.append(i)
a

returns: 'NoneType' object has no attribute 'append'

解决方案

The list.append function does not return any value, it just add the value to the list you are using to call that method.

In the first loop round you will assign None (because the no-return of append) to a, then in the second round it will try to call a.append, as a is None it will raise the Exception you are seing

You just need to change it to:

a=[]
for i in range(5):    
    a.append(i)
a # the list with the new items.

这篇关于Python:在for循环中列出append()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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