[英]Python: compact/one liner for the for loop
我有以下有效的代碼,並提供了預期的輸出。
#!/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')]
使用xmltodict,您可能可以做類似
data = xmltodict.parse("Document.XML")
val = data['arch']['pro']['@label']
您必須使用我的偽代碼來添加多個val
的列表理解,但以上內容應說明基本用法(請參見git頁面)。 Bruno Rocha最近在博客上發布了xmltodict。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.