我可以在列表中显示每个列表项的位置而无需创建自己的计数器吗?

Ama*_*nda 1 python loops for-loop

我试图解析与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
Run Code Online (Sandbox Code Playgroud)

这会抛出一些揭示信息:

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 
Run Code Online (Sandbox Code Playgroud)

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

mgi*_*son 6

你在找enumerate

for c,cell in enumerate(cells):
    ....
Run Code Online (Sandbox Code Playgroud)