更新时间:2023-11-28 23:17:04
您可以像这样压缩整个代码
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, return True
.
如果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.