2013-04-08 55 views
3

的名單得到指數我有字符串列表清單,如: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' 

這對蘋果和椅子失敗,得到一個索引錯誤。另外,這對我來說看起來很糟糕。有沒有更好的做法呢?

回答

3

返回包含元組的列表(外部列表索引,內部列表索引),設計,使得您要尋找的項目可以在多個內部列表:

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

在計算我的行中,如果將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

要獲得名單列表的指數蟒蛇:

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]