Skip to main content
 首页 » 编程设计

python之使用嵌套 ifs 的替代方法

2024年10月17日8haluo1

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 个项目,则任何实现都不应该有任何问题,因为它们会立即从层中返回。