0

I want to implement the following code in more of a pythonic way:

odd_rows = table.findAll('tr', attrs = {'class':'odd'}) #contain all tr tags
even_rows = table.findAll('tr', attrs = {'class':'even'})

for rows in odd_rows:              #rows equal 1 <tr> tag 
    rows.findAll('td')             #find all the <td> tags located in that one <tr> tag
    for row in rows.findAll('td'): #find one <td> tag
        print row                  #print that <td> tag

for rows in even_rows:
    rows.findAll('td')
    for row in rows.findAll('td'):
        print row

the line row.findAll('td') shows my logic

4

2 回答 2

3
for cls in ("odd", "even"):
    for rows in table.findAll('tr', class_=cls):
        for row in rows.findAll('td'):
            print row
于 2013-06-14T01:37:47.470 回答
2

也许:

for row in table.findAll('tr', attrs = {'class':'odd'}) + table.findAll('tr', attrs = {'class':'even'}):
    for cell in row.findAll('td'):
        print cell

从性能的角度来看,您的原始代码更好。合并两个列表确实会使用资源。

但是,除非您正在为 Google scale 编写代码,否则我同意这句话。

必须编写程序供人们阅读,并且只是偶然地供机器执行。
- Hal Abelson,计算机程序的结构和解释

有不止一种方法可以做到这一点。以您认为最易读的方式编写代码。计算机可以计算出细节。

于 2013-06-14T01:39:16.077 回答