James Hallen
James Hallen

Reputation: 5004

Pythonic way to iterate through loops

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

Upvotes: 0

Views: 153

Answers (2)

000
000

Reputation: 27227

Perhaps:

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

From a performance standpoint, your original code is better. Combining two lists does use resources.

However, unless you are writing code for Google scale, I agree with this quote.

Programs must be written for people to read, and only incidentally for machines to execute.
- Hal Abelson, Structure and Interpretation of Computer Programs

There is more than one way to do it. Write code the way that you feel is most readable to you. The computer can figure out the details.

Upvotes: 2

David Robinson
David Robinson

Reputation: 78590

for cls in ("odd", "even"):
    for rows in table.findAll('tr', class_=cls):
        for row in rows.findAll('td'):
            print row

Upvotes: 3

Related Questions