Python,从列表中的列表中获取索引

5

我有一个字符串列表的列表,就像这样:

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'

这对于苹果和椅子会出现索引错误。此外,在我看来这样做不太好。有更好的方法吗?

8个回答

4

返回一个元组列表,每个元组包含(外部列表索引,内部列表索引),旨在使您要查找的项目可以位于多个内部列表中:

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

对于Python 3,您将想要使用range() - Carsten
请注意,对于您正在搜索的字符串的多个出现,您只会找到第一个条目。我添加了一个可以找到所有出现的答案。 - Carsten

1
如果您想使用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

0
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

0
我会创建一个字典来将项目映射到它们的索引:
>>> import numpy as np
>>> l = [['apple','banana','kiwi'],['chair','table','spoon']]
>>> a = np.array(l,dtype=object)
>>> a
array([[apple, banana, kiwi],
       [chair, table, spoon]], dtype=object)
>>> d = {s:idx for (idx),s in np.ndenumerate(a)}
>>> d['apple']
(0, 0)
>>> d['chair']
(1, 0)

numpy + ndenumerate 可以很好地创建索引,但这并非必需。当然,如果您可以创建一次索引,然后在后续搜索中重复使用它,那么效率会更高。


0
一种方法是利用enumerate
l = [['apple','banana','kiwi'],['chair','table','spoon']]
s = ['apple','banana','kiwi','chair','table','spoon']

for a in s:
    for i, ll in enumerate(l):
        for j, b in enumerate(ll):
            if a == b:
                print a, i, j

0
在计算i的那一行中,如果你将argwhere应用于整个列表而不是每个子列表,你已经得到了答案。没有必要再次搜索j。
def ind(s):
    match = np.argwhere(np.array(l == s))
    if match:
        i, j = match[0]
    else:
        return -1, -1

这将返回你正在搜索的字符串的第一个出现的索引。

此外,你可能要考虑到随着问题复杂度增加,该方法所受的影响。该方法会遍历列表中的每个元素,因此运行时间成本随着列表变大而增加。所以,如果你要在列表中查找的测试字符串数量也增加了,你可能想考虑使用字典来创建一次查找表,然后后续对测试字符串的搜索成本更低。

def make_lookup(search_list):
    lookup_table = {}
    for i, sublist in enumerate(list):
        for j, word in enumerate(sublist):
            lookup_table[word] = (i, j)
    return lookup_table

lookup_table = make_lookup(l)

def ind(s):
    if s in lookup_table:
        return lookup_table[s]
    else:
        return -1, -1

0

获取Python中列表的列表索引:

theList = [[1,2,3], [4,5,6], [7,8,9]]
for i in range(len(theList)):
    if 5 in theList(i):
        print("[{0}][{1}]".format(i, theList[i].index(5))) #[1][1]

第3行应为theList[i]而不是theList(i) - bobsacameno

0

这个解决方案将找到您正在搜索的字符串的所有出现:

l = [['apple','banana','kiwi','apple'],['chair','table','spoon']]

def findItem(theList, item):
       return [(i, j) for i, line in enumerate(theList)
               for j, char in enumerate(line) if char == item]

findItem(l, 'apple') # [(0, 0), (0, 3)]
findItem(l, 'spoon') # [(1, 2)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接