use*_*896 5 python indexing list
我有一个字符串列表列表,如下所示:
l = [['apple','banana','kiwi'],['chair','table','spoon']]
Run Code Online (Sandbox Code Playgroud)
给定一个字符串,我希望它在 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'
Run Code Online (Sandbox Code Playgroud)
这对于苹果和椅子失败,得到一个索引错误。此外,这对我来说看起来很糟糕。有没有更好的方法来做到这一点?
返回包含(外部列表索引,内部列表索引)的元组列表,其设计使得您要查找的项目可以位于多个内部列表中:
l = [['apple','banana','kiwi'],['chair','table','spoon']]
def findItem(theList, item):
return [(ind, theList[ind].index(item)) for ind in xrange(len(theList)) if item in theList[ind]]
findItem(l, 'apple') # [(0, 0)]
findItem(l, 'spoon') # [(1, 2)]
Run Code Online (Sandbox Code Playgroud)