我想让列表中的所有内容都是“垃圾邮件”,但是我无法调用垃圾邮件列表。
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
答案 0 :(得分:3)
错误消息指出,列表对象不可调用。
您应该使用方括号(即spam[i]
而不是spam(i)
来访问列表中的项目。
此外,在列表上进行迭代时,您可以避免大部分时间使用范围:
spam = ['apples' , 'bananas' , 'tofu' , 'cats']
for thing in spam:
print(thing , end = ',')
答案 1 :(得分:0)
在python中进行列表切片的过程类似于spam[i]
,在某些内容上使用常规方括号总是意味着“调用”它,意味着将其视为要调用的函数。
答案 2 :(得分:0)
您的问题在于此行:
print(spam(i) , end = ',')
在这种情况下,由于您将i
括在圆括号中,因此Python尝试将spam()
作为函数同时将i
作为参数执行。要解决此问题,请改用方括号:
print(spam[i] , end = ',')