Python嵌套列表递归搜索 [英] Python nested list recursion search
问题描述
给出一个嵌套列表L(这样L的每个元素要么是一个整数,要么是一个列表,列表本身可以 包含整数或列表,这些列表或表可能反过来……等)返回True i s在L中.
Given a nested list L (such that each element of L is either an integer, or a list, which may itself contain integers, or lists, which may in turn.... etc) return True i s is in L.
search([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], 8)
应返回True.
这是我到目前为止所拥有的:
Here is what I have so far:
def search (L,s):
"""(list, anytype) _> Bool
Returns true iff s is present in L
"""
if L:
if L[0] == s:
return True
else:
return search (L[1:], s)
else:
return False
如果列表没有嵌套,或者像这样嵌套(嵌套元素是最后一个元素),则当前代码适用于列表:
This current code works for a list if it isn't nested, or if it is nested like so (the nested element is the last element):
[1, 2, 3, [4, 5]]
但不适用于以下内容:
[1, 2, [3, 4], 5]
如何更改代码,使其适用于嵌套列表?嵌套元素在列表中的任意位置,而不是最后一个元素?
How can I change my code so that it works for a nested list? with the nested element being anywhere in the list not strictly the last element?
感谢任何帮助!
对不起,忘记指定它需要递归.
Sorry, forgot to specify that it needs to be recursive.
推荐答案
您可以像这样压缩整个代码
You can squeeze your entire code like this
def search(current_item, number):
if current_item == number: return True
return isinstance(current_item, list) \
and any(search(item, number) for item in current_item)
您可以像这样测试它
for i in range(12):
print i, search([1, [2, 3], 4, [5, [6 , [], [8, 9]], 10]], i)
输出
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True
10 True
11 False
逻辑是这样的,
-
如果
current_item
等于我们要查找的数字,请返回True
.
If the
current_item
is equal to the number we are looking for, returnTrue
.
如果current_item
不是list的实例,则在这种情况下为数字.如果它是一个数字并且不等于number
,我们应该返回False
.
If the current_item
is not an instance of list, then it is a number in this case. If it is a number and it does not equal to number
we should return False
.
如果current_item
是列表,则遍历它的每个元素,并检查是否有任何元素具有number
. any
在获得第一个True
值后立即返回.
If the current_item
is a list, then go through each and every element of it and check if any of the elements has number
. any
returns immediately after getting the first True
value.
这篇关于Python嵌套列表递归搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!