簡體   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