首页 > 解决方案 > 为什么我在这个 python 代码中得到一个 TypeError?

问题描述

我想获取“垃圾邮件”列表中的每个项目,但我无法调用垃圾邮件列表..

spam = ['apples' , 'bananas' , 'tofu' , 'cats']
i = 0
n = len(spam)


for i in range (0, n):
    if i <= n :
        print(spam(i) , end = ',')
        i += 1
    else:
        break
Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\commaCode.py", line 9, in <module>
    print(spam(i) , end = ',')
TypeError: 'list' object is not callable

标签: python

解决方案


正如错误消息指出的那样,列表对象是不可调用的。您应该使用方括号(即spam[i],而不是spam(i))访问列表中的项目。

此外,在对列表进行迭代时,您可以避免在大多数情况下使用范围:

spam = ['apples' , 'bananas' , 'tofu' , 'cats']

for thing in spam:
    print(thing , end = ',')

推荐阅读