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:
		...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章