Index of an element in a nested list(嵌套列表中元素的索引)
本文介绍了嵌套列表中元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
几天来,我一直在努力锻炼身体。 给定的是以下嵌套列表:
[1, [5, 62, 6], 4, [99, [100, 200, 600, [1000, [2000]]]], [74, 41, 16], 7, [8], [[[400]]]]
和该函数体:
def find_element(liste, find, index = 0):
我必须在嵌套列表中找到一个元素,该函数应该返回找到的元素的确切索引,例如5的索引为[1,0],2000的索引为[3,1,3,1,0]。 该函数必须是递归的。
我的问题是,如果元素不在列表中,则函数必须返回False。
这是我的代码:
def find_element(liste, find, index = 0):
indexList = []
if len(liste) == index:
return indexList
if liste[index] == find:
indexList.append(index)
else:
if type(liste[index]) == list:
indexList.extend(find_element(liste[index], find))
if indexList:
indexList.insert(0, index)
else:
indexList.extend(find_element(liste, find, index + 1))
return indexList
我尝试了第二个函数,该函数在列表为空时返回False,或者在索引为0且indexList为空时返回If条件,但我得到的都是RecursionError或TypeError。
推荐答案
Ajax1234的答案是有效的,但如果您需要更简单一点的东西,这可能更好:
def find_idx(input_list, elem):
for i in range(len(input_list)):
if isinstance(input_list[i], list):
result = find_idx(input_list[i], elem)
if result:
return [i] + result
elif input_list[i] == elem:
return [i]
return False
input_list = [1, [5, 62, 6], 4, [99, [100, 200, 600, [1000, [2000]]]], [74, 41, 16], 7, [8], [[[400]]]]
print(find_idx(input_list, 2000))
# Output: [3, 1, 3, 1, 0]
这基本上是DFS(https://en.wikipedia.org/wiki/Depth-first_search)。如果您将数据结构看作一棵树,那么列表条目就是节点,因为它们本身可以包含其他列表,就像树中的节点可以指向其他节点一样。神奇之处在于,如果在方法的末尾什么都没有找到,则返回False
,但在到达该点之前递归搜索所有子列表。此外,您还必须检查您的列表条目本身是否是一个列表,但这只是一个类比,即树可以具有指向其他节点的节点,也可以具有不指向其他节点的节点(在本例中为叶节点或普通的旧数)。
这篇关于嵌套列表中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:嵌套列表中元素的索引


基础教程推荐
猜你喜欢
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01