Skip to main content
 首页 » 编程设计

Python:for循环的紧凑/一个衬里

2025年05月04日17mengfanrong

我有以下有效的代码,并给出了预期的输出。

#!/bin/env python 
import xml.etree.ElementTree as e 
tree = e.parse("Document.XML") 
root = tree.getroot() 
vals=[] 

代码的以下部分可以是单行代码还是更紧凑的代码?

for ch in root.findall('arch'): 
    for gc in ch.findall('pro'): 
        vals.append(gc.get('label')) 

我的 libxml2 版本不支持 xpath,请不要建议该选项。 XMl 文件如下所示:

<projects> 
  <arch name="arch1"> 
    <pro label="A1" type="B1" state="C1"/> 
    .... 
  </arch> 
  .... 
</projects> 

请您参考如下方法:

当然,使用带有两个循环的列表推导式:

vals = [gc.get('label') for ch in root.findall('arch') for gc in ch.findall('pro')]