以前我有一個關於查找元素是否存在於嵌套列表中的問題,並在下面的鏈接中獲得了響應。搜索多維列表中的元素並返回子列表號?
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.
上述查詢的任何線索?請放下您的評論...
感謝您的答覆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
我編輯了我的答案一點。但我明白了。字符串本身是可迭代的,我只用int進行測試。一些調整會做。給我一分鐘;) – schwobaseggl
現在它應該工作! – schwobaseggl