的名單得到指數我有字符串列表清單,如:Python中,從列表
l = [['apple','banana','kiwi'],['chair','table','spoon']]
給定一個字符串,我想它在L索引。嘗試與numpy,這是我最終與:
import numpy as np
l = [['apple','banana','kiwi'],['chair','table','spoon']]
def ind(s):
i = [i for i in range(len(l)) if np.argwhere(np.array(l[i]) == s)][0]
j = np.argwhere(np.array(l[i]) == s)[0][0]
return i, j
s = ['apple','banana','kiwi','chair','table','spoon']
for val in s:
try:
print val, ind(val)
except IndexError:
print 'oops'
這對蘋果和椅子失敗,得到一個索引錯誤。另外,這對我來說看起來很糟糕。有沒有更好的做法呢?