TypeError: list indices must be integers, not str Python

前端 未结 5 482
再見小時候
再見小時候 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:41

    Do not use the name list for a list. I have used mylist below.

    for s in mylist:
        t = (mylist[s], 1)
    

    for s in mylist: assigns elements of mylist to s i.e s takes the value 'abc' in the first iteration and 'def' in the second iteration. Thus, s can't be used as an index in mylist[s].

    Instead, simply do:

    for s in lists:
        t = (s, 1)
        map_list.append(t)
    print map_list
    #[('abc', 1), ('def', 1)]
    

提交回复
热议问题