TypeError: list indices must be integers, not str Python

前端 未结 5 487
再見小時候
再見小時候 2020-11-30 15:20

list[s] is a string. Why doesn\'t this work?

The following error appears:

TypeError: list indices must be integers, not str

5条回答
  •  囚心锁ツ
    2020-11-30 15:29

    it should be:

    for s in my_list:     # here s is element  of list not index of list
        t = (s, 1)
        map_list.append(t)
    

    i think you want:

    for i,s in enumerate(my_list):  # here i is the index and s is the respective element
        t = (s, i)
        map_list.append(t)
    

    enumerate give index and element

    Note: using list as variable name is bad practice. its built in function

提交回复
热议问题