2016-04-28 70 views
1

以前我有一個關於查找元素是否存在於嵌套列表中的問題,並在下面的鏈接中獲得了響應。搜索多維列表中的元素並返回子列表號?

Search of Element inside a multi-dimensional List Not Working. Any Clue

在想,如果功能可能也發出它說在哪個子列表確實元素存在的價值?下面是它說的代碼,如果該元素退出與否:

def in_nested_list(item, x): 
    if not isinstance(x, list): 
     return x == item 
    else: 
     return any(in_nested_list(item, ix) for ix in x) 

list1 = [] 
list1.append([['red'], ['blue'], ['bla']]) 

print list1 

list1.append([['hello'], ['blue'], ['bla']]) 
print list1 

if in_nested_list('hello', list1): 
    print "Found Hello" 
else: 
    print "Not Found Hello" 

在想,我怎麼能更改功能,也可以說在這基礎上特定的子列表確實元素退出,這樣我可以追加進一步的數據子列表。

a。從上面的例子中,if條件會打印出Hello。但是,如果它也返回或保存一個輸出變量,如上面的例子中的sublist_no,即子列表1,以便我可以追加更多的變量。例如:現在輸出返回TRUE並且子列表號碼爲1,以便我可以在調用該函數後執行以下過程。

list1[sublist_no].append(['Bug']) 

說,如果我搜索元素紅色,輸出將是TRUE與sublist_no爲0,這樣我就可以添加一些變量來第一次名單。 list1[sublist_no].append('[Rasberry]') # i.e. onto the first sub-list.

上述查詢的任何線索?請放下您的評論...

回答

0

因爲你原來的功能,可以應對的不僅僅是列表的列表要複雜得多嵌套結構,所以如果您的嵌套「index」功能:

def in_nested_list(item, x): 
    if item == x: 
     return [] 
    if isinstance(x, list): 
     for i, ix in enumerate(x): 
      r = in_nested_list(item, ix) 
      if r != -1: 
       return [i] + r # highest level index plus path in sublist 
    return -1 # not found in any (nested) sublist 

# if not found at all: return -1 
# if item == x: return [] 
# else: return [a, b, c] such that item == x[a][b][c] 

> in_nested_list(3, [[1, 2], [3, 4]]) 
[1, 0] 

> in_nested_list(3, [[1, 2], [[5, 3], 4]]) 
[1, 0, 1] 

> in_nested_list(3, 3) 
[] 

> in_nested_list(3, [1, 2]) 
# -1 

這可以讓你追加任何你選擇的嵌套級別的東西。至於你的問題,你簡單結構中子列表的索引應該是in_nested_list(...)[0](如果存在的話,否則引發錯誤)。

+0

感謝您的答覆Schwobaseggl ..我試圖運行的例子,但不知其進入循環錯誤: 文件「./listeg_sch.py​​」,8號線,在in_nested_list X = in_nested_list(項目,九) 文件「 ./listeg_sch.py​​「,第4行,在in_nested_list if item == x: RuntimeError:最大遞歸深度超出cmp 不知所措.. – Vimo

+0

我編輯了我的答案一點。但我明白了。字符串本身是可迭代的,我只用int進行測試。一些調整會做。給我一分鐘;) – schwobaseggl

+0

現在它應該工作! – schwobaseggl

0

我利用槓桿來修改你的功能。

def in_nested(item, container): 
    if not isinstance(container, list): 
     raise TypeError 
    for elem in container: 
     if isinstance(elem, list): 
      found = in_nested(item, elem) 
      if not found: 
       pass 
      elif isinstance(found, bool): 
       # Item is present in this list 
       return elem 
       # List containing item is present in this container 
       # Comment above return to use it. 
       return container 
      else: 
       # Return the deepest list and not the most outer list containing it. 
       return found 
     else: 
      return item == elem 


_input = [[['red'], ['blue'], ['bla']], [['hello'], ['blue'], ['bla']]] 
out = in_nested('hello', _input) 
if out: 
    print "Found Hello", out 
else: 
    print "Not Found Hello" 

out.append('new') 
print 'Added new to original input', _input 

out = in_nested('Hello', _input) # hello with capital H 
if out: 
    print "Found Hello", out 
else: 
    print "Not Found Hello" 

# Prints: 
# Found Hello ['hello'] 
# Added new to original input [[['red'], ['blue'], ['bla']], [['hello', 'new'], ['blue'], ['bla']]] 
# Not Found Hello 

注意:它給你的目標列表本身,如果項目存在,否則無。您不必再次查找列表。只需附加到結果。

+0

非常感謝您的答覆Anshu ..所以這基本上是返回最內層列表本身..所以我也可以得到內部列表號碼?類似的東西?例如:在上面的情況下,內部列表號是1,因爲'你好'出現在第二個內部列表中? – Vimo

+0

根據您的要求,我不明白你爲什麼需要列表號碼。但如果你需要它,像@schwobaseggl這樣的答案會更有意義。 –

+0

Hello Anshu ..確實..當你運行你提供的情況下,它基本上加入到內部列表本身,如: [[['red'],['blue'],['bla']],[['' [''''],[''''],['''']] 而不是將新的元素添加到第二個內部列表的末尾.. [[['red'],['藍色'],['bla']],[['hello'],['blue'],['bla'],['new']]] 因爲在哪個內部列表中, ,我想添加更多的元素到列表的末尾,而不是在列表本身..所以我只是在尋找內部列表編號,所以我可以添加類似於,_input [1] .append(['' new'])以及其他幾個變量 – Vimo