繁体   English   中英

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

[英]Python, get index from list of lists

我有一个字符串列表列表,如下所示:

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'

这对于苹果和椅子失败,得到一个索引错误。 此外,这对我来说看起来很糟糕。 有没有更好的方法来做到这一点?

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

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

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

我会创建一个字典来将项目映射到它们的索引:

>>> 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非常适合创建索引,但绝对没有必要。 当然,如果您可以创建一次索引,然后将其重用于后续搜索,这将是最有效的。

一种方法是使用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

在计算 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

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

此解决方案将找到您正在搜索的所有字符串:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM