TypeError: list indices must be integers, not str Python

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

    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)
    

    Output:

    >>> 
    [0, 1, 2, 3, 4, 5]
    >>> 
    

    This is what you want exactly.

    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)
    

    Output:

    >>> 
    [0, 1]
    >>> 
    

提交回复
热议问题