<p>我有一个字符串列表,如下所示:</p>
<pre><code>l = [['apple','banana','kiwi'],['chair','table','spoon']]
</code></pre>
<p>给定一个字符串,我想要它在l中的索引。使用numpy进行实验,这就是我最终得到的结果:</p>
<pre><code>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'
</code></pre>
<p>这对于苹果和椅子来说是失败的,它得到了一个索引器。而且,这对我来说很糟糕。有什么更好的方法来做这个吗?</p>
<pre><code>l = [['apple','banana','kiwi'],['chair','table','spoon']]
def search(lst, item):
for i in range(len(lst)):
part = lst[i]
for j in range(len(part)):
if part[j] == item: return (i, j)
return None
</code></pre>