l.append[i],对象不可下标? [英] l.append[i], object is not subscriptable?

查看:25
本文介绍了l.append[i],对象不可下标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做时:

l = []
for i in range(10):
    if i%3 == 0 or i%5 == 0:
        l.append[i]
print sum(l)

我明白了

Traceback (most recent call last):
  File "PE1.py", line 4, in <module>
    l.append[i]
TypeError: 'builtin_function_or_method' object is not subscriptable

真的没有办法附加所有通过条件的 i 吗?

Is there really no way append all the i's that pass the condition?

推荐答案

append 是一个方法,你使用函数调用语法.

append is a method, you use function call syntax.

l.append(i)

此外,在这种情况下,更优雅的方法是使用列表理解:

Also, more elegant approach in cases like this is to use list comprehension:

l = [i for i in range(10) if i % 3 == 0 or i % 5 == 0]

这篇关于l.append[i],对象不可下标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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