前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >完美解决丨2. `TypeError: list indices must be integers or slices, not str`

完美解决丨2. `TypeError: list indices must be integers or slices, not str`

作者头像
不吃西红柿
发布2023-04-21 21:06:21
6.1K0
发布2023-04-21 21:06:21
举报
文章被收录于专栏:信息技术智库
  1. ‘tuple’ object does not support item assignment

原因:

tuple 是一个元素不可变的列表,如果尝试对 tuple 中的某个元素进行修改,会报错。

解决办法:

需要将 tuple 转换为 list,然后再把 list 转换为 tuple。

示例:

代码语言:javascript
复制
```python strs = ('a', 'bc', 'def') strs[1] = 'bcd' 报错   
strs = list(strs) strs[1] = 'bcd' strs = tuple(strs) ``` 
  1. TypeError: list indices must be integers or slices, not str

原因:

list 中的元素只能通过整数来访问,如果使用字符串,会报错。

解决办法:

可以通过 .index() 方法来查找字符串在 list 中的位置,然后通过整数来访问。

代码语言:javascript
复制
示例:
 ```python strs = ['a', 'bc', 'def'] strs['bc'] = 'bcd' 报错   
index = strs.index('bc') strs[index] = 'bcd' ``` 
  1. AttributeError: 'function' object has no attribute 'x'

原因:

如果要从函数中访问其他函数,需要使用 self 参数。

解决办法:

将其他函数的调用改为 self.x() 。

示例:

代码语言:javascript
复制

 ```python class A: def   init(self): self.x = 1 def y(self): return self.x   
a = A() a.y() 1
x = a.y x() 报错
x = x.self x() 1 ``` 

  1. NameError: name 'x' is not defined

原因:

如果要使用某个变量,需要确保该变量已经声明。

解决办法:

确保该变量已经声明。

示例:

代码语言:javascript
复制
```python x = 1 print(x) 1 print(y) 报错 ```   
  1. SyntaxError: invalid syntax

原因:

语法错误,可能是缩进不正确,或者缺少某个符号。

解决办法:

检查代码,确认是否缩进正确,是否缺少某个符号。

代码语言:javascript
复制
示例:
 ```python if x 5: print(x)   
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-04-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档