get index of character in python list

后端 未结 3 1673
你的背包
你的背包 2020-12-19 00:20

What would be the best way to find the index of a specified character in a list containing multiple characters?

相关标签:
3条回答
  • 2020-12-19 00:51

    Probably the index method?

    a = ["a", "b", "c", "d", "e"]
    print a.index("c")
    
    0 讨论(0)
  • 2020-12-19 01:04
    >>> ['a', 'b'].index('b')
    1
    

    If the list is already sorted, you can of course do better than linear search.

    0 讨论(0)
  • 2020-12-19 01:12

    As suggested by others, you can use index. Other than that you can use enumerate to get both the index as well as the character

    for position,char in enumerate(['a','b','c','d']):
        if char=='b':
            print position
    
    0 讨论(0)
提交回复
热议问题