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