get index of character in python list

倾然丶 夕夏残阳落幕 提交于 2019-12-18 05:44:45

问题


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


回答1:


>>> ['a', 'b'].index('b')
1

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




回答2:


Probably the index method?

a = ["a", "b", "c", "d", "e"]
print a.index("c")



回答3:


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


来源:https://stackoverflow.com/questions/3847472/get-index-of-character-in-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!