递归如何访问嵌套列表?

2024-04-20 04:47:33 发布

您现在位置:Python中文网/ 问答频道 /正文

def count_even(obj):
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list.  Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.

@param int|list obj: object to count even numbers from
@rtype: int

>>> count_even(3)
0
>>> count_even(16)
1
>>> count_even([1, 2, [3, 4], 5])
2
"""
count = 0
if isinstance(obj, int):
    if obj % 2 == 0:
        return 1
    else:
        return 0
else:
    for i in obj:
        count += count_even(i)
    return new

我不明白在最后第二行“count+=count_-even(I)”,“recursion”是如何访问[1,2,[3,4],5]的嵌套列表[3,4]。在

for循环不会遍历每一项{i=0(1),i=1(2),i=2([3,4]),i=3(5)},寻找一个int,并且没有if语句触发器[3,4],因为它是一个列表吗?在


Tags: ofinanobjnumberreturnifis
1条回答
网友
1楼 · 发布于 2024-04-20 04:47:33

该函数能够访问嵌套列表[3, 4],因为正如您所述,值[3, 4]跳过了第一个if(因为[3, 4]不是int,然后执行else。在else中,您将在[3, 4]上得到另一个循环,然后检查3和{}的奇数/均匀度。在

这里有一条线索可以帮助你理清思路:

obj = [ 1, 2, [3, 4], 5 ]
count_even(obj) =>
  count_even([ 1, 2, [3, 4], 5]) =>
    is obj an `int`?  No =>
      for i in [ 1, 2, [3, 4], 5] =>
        count_even(1) =>
           is 1 an int?  Yes => return 0 because 1 is odd
        count_even(2)
           is 2 an int?  Yes => return 1 because 2 is even
        count_even([3, 4]) =>
           is [3, 4] an int?  No =>
             for i in [3, 4] =>
               count_even(3) =>
                 Is 3 an int?  Yes => return 0 because 3 is odd
               count_even(4) =>
                 Is 4 and int?  Yes => return 1 because 4 is even
        count_even(5) =>
           is 5 an int?  Yes => return 0 because 5 is odd

相关问题 更多 >