繁体   English   中英

Python 递归返回不同

[英]Python recursion return differs

python 撤回的返回不同,我不明白为什么:

from bs4 import BeautifulSoup


def recurse_table(table, table_list):
    if table.find_next("table") is not None:
        recurse_table(table.find_next("table"), table_list)
    table_list.append(table)
    return table_list


fp = open("tc4400_cs_2.html")
soup = BeautifulSoup(fp.read(), features="html.parser")
print(len(recurse_table(soup.find("table"), [])))

返回正确的长度 (4)。

然而

from bs4 import BeautifulSoup


def recurse_table(table, table_list):
    if table.find_next("table") is not None:
        recurse_table(table.find_next("table"), table_list)
    return table_list.append(table)


fp = open("tc4400_cs_2.html")
soup = BeautifulSoup(fp.read(), features="html.parser")
print(len(recurse_table(soup.find("table"), [])))

返回 TypeError: 'NoneType' 类型的 object 没有 len()

我错过了什么?

回报不同,因为您返回的内容不同。 .append()方法修改table_list但不返回它,而是返回一个None 如果要返回列表,则应将 append table放在一行中,然后在下一行返回列表,就像您在第一个代码中所做的那样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM