Skip to main content
 首页 » 编程设计

python之我可以在不创建自己的计数器的情况下显示每个列表项在列表中的位置吗

2025年05月04日18shanyou

我正在尝试使用 BeautifulSoup 解析一个表,并发现在浏览它时了解我正在查看的行和列会很有帮助。现在我得到了这个:

for table in soup.find_all("table", {"class":"foo"}): 
    r = 0 
    for row in table.find_all('tr'):             
        cells = row.find_all("td") 
        c = 0 
        for cell in cells: 
            print "row", r, "cell", c 
            print cell.attr 
            c += 1 
        r +=1 

这转储了一些揭示信息:

row 0 cell 0  
row 1 cell 0  
row 1 cell 1  
row 1 cell 2  
row 1 cell 3  
row 1 cell 4  
row 2 cell 0  
row 2 cell 1  
row 3 cell 0  
row 3 cell 1  

由于某种原因,行 [1] 有很多额外的列。方便知道。我想知道的是......是否有一个内置变量可以报告我在列表中的位置。

请您参考如下方法:

你在寻找enumerate吗?

for c,cell in enumerate(cells): 
    ....