这是我的迭代解决方案:
def exists(key, arg):
if not arg:
return False
else:
for element in arg:
if isinstance(element,list):
for i in element:
if i==key:
return True
elif element==key:
return True
return False
print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]))
但是,我的洛杉矶想要一个双递归函数来解决这个问题。
我的尝试:
def exists(key, arg):
if not arg: //base case
return False
elif arg[0]==key: //if we find the key from the first trial
return True
else:
return (exists(arg[0:],key))
这行不通;它不应该,因为没有停止。此外,它不考虑列表列表;我不知道该怎么做。
感谢任何回答、评论等
最佳答案
def exists(k, l):
if not isinstance(l, list):
return False
if k in l:
return True
return any(map(lambda sublist: exists(k, sublist), l))
关于python - 如何在嵌套列表中查找给定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39641229/