Python3报错:TypeError: list indices must be integers or slices, not str
问题
示例代码:
strlist = ['a','b','c']
for i in strlist:
if strlist[i] > 0:
...
报错:TypeError: list indices must be integers or slices, not str
解决
原因很简单:python里对list
进行for遍历,默认第一个参数为list
中的元素,而上面代码中的strlist[i]
实际上strlist['a']
。因此想要遍历list
,对其中的string
类型元素进行长短判断,应该将代码改为:
strlist = ['a','b','c']
for i in strlist:
if i > 0:
...
还没有评论,来说两句吧...