获取python列表中字符的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3847472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:02:18  来源:igfitidea点击:

get index of character in python list

pythonindexingcharacter

提问by a sandwhich

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

在包含多个字符的列表中查找指定字符的索引的最佳方法是什么?

采纳答案by AndiDog

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

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

如果列表已经排序,你当然可以比线性搜索做得更好。

回答by Jim Brissom

Probably the indexmethod?

大概是什么index方法?

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

回答by Jim Brissom

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

正如其他人所建议的那样,您可以使用index. 除此之外,你可以用enumerate获得两个index还有character

for position,char in enumerate(['a','b','c','d']):
    if char=='b':
        print position