在Python列表中获取字符索引
在一个包含多个字符的列表中,找到指定字符的索引(位置)最好的方法是什么?
4 个回答
1
正如其他人所建议的,你可以使用 index
。除此之外,你还可以使用 enumerate
,这样可以同时获取 index
(索引)和 character
(字符)。
for position,char in enumerate(['a','b','c','d']):
if char=='b':
print position
5
可能是 index
方法吧?
a = ["a", "b", "c", "d", "e"]
print a.index("c")
33
>>> ['a', 'b'].index('b')
1
如果这个列表已经排好序了,那你当然可以用比线性搜索更好的方法来查找。