python - 为什么我在这个 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
解决方案
正如错误消息指出的那样,列表对象是不可调用的。您应该使用方括号(即spam[i]
,而不是spam(i)
)访问列表中的项目。
此外,在对列表进行迭代时,您可以避免在大多数情况下使用范围:
spam = ['apples' , 'bananas' , 'tofu' , 'cats']
for thing in spam:
print(thing , end = ',')
推荐阅读
- kubernetes - 无法使用新上下文连接到 Kubernetes
- batch-file - How can I set a shorcut key in VS code to run a .bat file in my working directory?
- elasticsearch - 考虑到输入的大小,有没有办法估计在 ElasticSeearch 的完成建议器中构建的内存 FST 的大小?
- angular - Display Unique values of mat-select that gets data from Angular filtered dataSource
- java - 使用 md5 哈希比较 docx 文件的问题
- css - CSS降低/削减边缘
- c# - 无法从日期类型中提取日期部分
- apache-kafka - 如何在 Spring Kafka 中实现消息排序
- c++ - 如何在 if constexpr 逻辑中使用静态断言?
- python - 如何在 django 的序列化器字段中设置上下文值?