Python,从列表中获取索引

2024-04-27 17:31:56 发布

您现在位置: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'

这对于苹果和椅子来说是失败的,它得到了一个索引器。而且,这对我来说很糟糕。有什么更好的方法来做这个吗?


Tags: 字符串innumpyapplefornptableval
3条回答

如果你想使用numpy,你不需要自己滚动:

import numpy as np
l = np.array([['apple','banana','kiwi'],['chair','table','spoon']])
s = ['apple','banana','kiwi','chair','table','spoon']

for a in s:
    arg = np.argwhere(l==a)
    print a, arg, tuple(arg[0]) if len(arg) else None
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

返回一个元组列表,该列表包含(外部列表索引、内部列表索引),设计为使您要查找的项可以位于多个内部列表中:

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)]

相关问题 更多 >