开发者

get index of character in python list

开发者 https://www.devze.com 2023-01-18 07:08 出处:网络
What would be the best way to find the index of a specified character in a list containin开发者_JS百科g multiple characters?>>> [\'a\', \'b\'].index(\'b\')

What would be the best way to find the index of a specified character in a list containin开发者_JS百科g multiple characters?


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

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


Probably the index method?

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


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


def lookallindicesof(char, list):
    indexlist = []
    for item in enumerate(list):
        if char in item:
            indexlist.append(item[0])
    return indexlist

indexlist = lookllindicesof('o',mylist1)
print(indexlist)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号