简体   繁体   English

循环遍历的Pythonic方法

[英]Pythonic way to iterate through loops

I want to implement the following code in more of a pythonic way: 我想更多地以Python方式实现以下代码:

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 row.findAll('td')显示了我的逻辑

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

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. 但是,除非您为Google scale编写代码,否则我同意这句话。

Programs must be written for people to read, and only incidentally for machines to execute. 必须编写程序供人们阅读,并且只能偶然地使机器执行。
- Hal Abelson, Structure and Interpretation of Computer Programs -Hal Abelson,计算机程序的结构和解释

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. 计算机可以找出细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM