如何在python中忽略for循环的第一行

时间:2016-11-04 20:50:57

标签: python for-loop lxml

使用两个for循环并获得此结果。

TABL  1st Line
TABL  
TABL  2nd Line
TABL  3rd Line

我想要的是:

TABL  1st Line
TABL  2nd Line
TABL  3rd Line

我正在使用lxml从xml中获取数据,就像这样。

for ent in row.xpath('entry/text()'):
   entry_text+=" "+ent
print("TABL    "+entry_text)

1 个答案:

答案 0 :(得分:0)

那是因为列表中有空/空数据。

你最好使用生成器理解:你可以有效地完成工作(字符串连接性能不佳),并且在一行中

"\n".join("TAB  "+e for e in row.xpath('entry/text()') if e.strip())
  • e循环遍历元素,并且只有在e不为空或只有空格时才在迭代器中发出一些内容(给定输出我们无法确定)。
  • 使用"\n"
  • 加入结果