使用嵌套ifs的替代方法

2024-10-01 13:43:13 发布

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

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))

这是使用BeautifulSoup解析HTML并在位置3(名字是1)找到链接。遵循这个链接。重复这个过程4次。有没有比使用嵌套循环更有效的方法?你知道吗


Tags: innoneforgetifhtmltagtags
2条回答

正如Peter和Anthony所说,您可以提取方法并使事情变得更简单。你知道吗

但是,一般来说,使用拇指规则,而不是嵌套的ifs,可以将条件更改为其补码和返回。你知道吗

在您的示例中:

if len(Ulist1) > 2: do_stuff() if len(Ulist1) > 2: do_more_stuff()

相反,你可以这样写:

if len(Ulist1) < 2: # the compement of the original condition return do_stuff() if len(Ulist1) < 2: # the compement of the original condition return do_more_stuff()

因此,您的代码可以编写如下:

if len(Ulist1) < 2:
    return

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:
    return

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:
    return

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))

当然,我建议你提取安东尼在上面写的方法。你知道吗

希望有帮助。你知道吗

你可以像彼得·伍德说的那样把它分解成一个函数。下面是一个可能的实现,它展示了基本概念。你知道吗

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个项,那么这两个实现都不应该有任何问题,因为它们将直接从层中返回。你知道吗

相关问题 更多 >