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

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

问题描述

在Python中,尝试对具有循环的列表执行最基本的附加功能:
不知道我在这里缺少什么:

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

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

推荐答案

list.append 函数不返回任何值(但 None ),它只是将值添加到用于调用该方法的列表中。

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

在第一轮循环中,您将分配 None (因为不返回添加到 a ,然后在第二轮尝试调用 a.append ,因为 a为None 会引发您看到的异常

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 seeing

您只需将其更改为:

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

编辑:正如Juan在评论中所说,它确实返回了某些内容,

As Juan said in comments it does return something, None

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

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