Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,从列表列表中获取索引_Python_List_Indexing - Fatal编程技术网

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

Python,从列表列表中获取索引,python,list,indexing,Python,List,Indexing,我有一个字符串列表,如下所示: 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(

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

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 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
很适合创建索引,但它绝对不是必需的。当然,如果您可以创建一次索引,然后将其重新用于后续搜索,这将是最有效的方法。

一种方法是使用
枚举

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

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

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

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

对于Python3,您需要使用
range()
请注意,对于要搜索的字符串的多次出现,您只能找到第一个条目。我添加了一个查找所有事件的答案。