python - 使用嵌套 if 的替代方法

标签 python python-2.7

for tag in tags:
    Ulist1.append(tag.get('href', None))

if len(Ulist1) > 2:
    print Ulist1[2]
    html = urllib.urlopen(Ulist1[2]).read()
    soup = BeautifulSoup(html)
    tags = soup('a')
    Ulist2 = list ()

    for tag in tags:
        Ulist2.append(tag.get('href', None))

    if len(Ulist2) > 2:
        print Ulist2[2]
        html = urllib.urlopen(Ulist2[2]).read()
        soup = BeautifulSoup(html)
        tags = soup('a')
        Ulist3 = list ()

        for tag in tags:
            Ulist3.append(tag.get('href', None))

        if len(Ulist3) > 2:
            print Ulist3[2]
            html = urllib.urlopen(Ulist3[2]).read()
            soup = BeautifulSoup(html)
            tags = soup('a')
            Ulist4 = list ()

            for tag in tags:
                Ulist4.append(tag.get('href', None))

这是使用 beautiful soup 来解析 HTML 并找到位置 3 处的链接(名字是 1)。请点击该链接。重复此过程 4 次。有没有比使用嵌套循环更有效的方法?

最佳答案

正如 Peter Wood 所说,您可以将其分解为一个函数。这是一种可能的实现,展示了基本概念。

def print_third_recursive(tags, iterations):
    Ulist = [tag.get('href', None) for tag in tags] # more pythonic
    if len(Ulist) > 2 && iterations :
        print Ulist[2]
        html = urllib.urlopen(Ulist[2]).read()
        soup = BeautifulSoup(html)
        new_tags = soup('a')
        use_third(new_tags, iterations - 1)

use_third_recursive(tags, 3)

如果您希望函数更简单,这绝对可以在不使用递归的情况下完成。

def print_third(tags):
    Ulist = [tag.get('href', None) for tag in tags] # more pythonic
    new_tags = []
    if len(Ulist) > 2:
        print Ulist[2]
        html = urllib.urlopen(Ulist[2]).read()
        soup = BeautifulSoup(html)
        new_tags = soup('a')
    return new_tags

print_third(
    print_third(
        print_third(tags)
    )
)

如果其中一个标签列表中没有 3 个项目,则两种实现都不会出现任何问题,因为它们只会从层中返回。

关于python - 使用嵌套 if 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539170/

相关文章:

python - 在 python 脚本中,我有插入查询,但是当我想在同一个查询中插入多个列时,它会给出错误

python - django manytomanyfield.add() 方法

python - Tensorflow:按名称获取所有权重张量

python - Mac + Anaconda 上的 Qt 设计器应用程序在哪里?

python - 忠实地保留已解析 XML 中的注释

google-app-engine - 在本地主机上导航到/_ah/admin 会产生未知的 404 错误

python - 比较两个字符串并在 python 中分配分数

python - 在 sqlalchemy 中加入值

python - 从类、函数、方法、模块打印文档字符串

python - 修复 Python 脚本的进程 ID