Finding the index of an item given a list containing it in Python
alist = ["foo", "bar", "baz", "bar"]
**********************************
alist.index('bar')
#1
找不到的話奉上 error, 不見得好啊
alist.index('haha')
#error ....
要用 try except 處理, 挺麻煩不是嗎
def sublist(e, l):
i = l.index(e)
sublist ('bar', alist)
#1
sublist ('err ', alist)
#-1
自寫
def match( a,alist ): return [i fori , v in enumerate( alist) if v == 'bar']match('bar', alist)
#[1, 3]
更簡化成
a = [ i for i,v in enumerate(alist) if v == 'bar' ]
上述挺簡潔的, 但太依賴 enumerate(), 用更基本的 range 寫呢?
[ i for i in range(len(alist)) if alist[i] == 'bar']
#[1, 3]
用 if .. in 呢?
其實本題並不要找 list, 這種就夠了
if 'bar' in alist: alist.index('bar')
#1