本文介紹了TypeError:列表索引必須是整數,而不是 str Python的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
list[s]
是一個字符串.為什么這不起作用?
list[s]
is a string. Why doesn't this work?
出現如下錯誤:
TypeError:列表索引必須是整數,而不是 str
TypeError: list indices must be integers, not str
list = ['abc', 'def']
map_list = []
for s in list:
t = (list[s], 1)
map_list.append(t)
推薦答案
list1 = ['abc', 'def']
list2=[]
for t in list1:
for h in t:
list2.append(h)
map_list = []
for x,y in enumerate(list2):
map_list.append(x)
print (map_list)
輸出:
>>>
[0, 1, 2, 3, 4, 5]
>>>
這正是你想要的.
如果你不想到達每個元素,那么:
If you dont want to reach each element then:
list1 = ['abc', 'def']
map_list=[]
for x,y in enumerate(list1):
map_list.append(x)
print (map_list)
輸出:
>>>
[0, 1]
>>>
這篇關于TypeError:列表索引必須是整數,而不是 str Python的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!