Python 习语 : List comprehension with limit of items

标签 python list-comprehension idioms

我基本上是在尝试这样做(伪代码,不是有效的 python):

limit = 10
results = [xml_to_dict(artist) for artist in xml.findall('artist') while limit--]

那么我怎样才能以简洁高效的方式编写代码呢? XML 文件可以包含 0 到 50 位艺术家之间的任何内容,我无法控制一次获取多少,而且 AFAIK,没有 XPATH 表达式来表示“让我最多 10 个节点”。

谢谢!

最佳答案

你在使用 lxml 吗?您可以使用 XPath 来限制查询级别中的项目,例如

>>> from lxml import etree
>>> from io import StringIO
>>> xml = etree.parse(StringIO('<foo><bar>1</bar><bar>2</bar><bar>4</bar><bar>8</bar></foo>'))
>>> [bar.text for bar in xml.xpath('bar[position()<=3]')]
['1', '2', '4']

你也可以 use itertools.islice to limit any iterable ,例如

>>> from itertools import islice
>>> [bar.text for bar in islice(xml.iterfind('bar'), 3)]
['1', '2', '4']
>>> [bar.text for bar in islice(xml.iterfind('bar'), 5)]
['1', '2', '4', '8']

关于Python 习语 : List comprehension with limit of items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3534676/

相关文章:

python - Matplotlib,水平条形图(barh)是倒置的

java - Camel 习惯用法根据消息正文中的值动态路由

performance - 如何着手编写核心函数,而不是使用命令式风格?

generator - 有没有办法避免在这个 Julia 表达式中创建数组?

python - 在列表理解中重复调用方法

javascript - 从对象中提取名称与测试匹配的属性

python - 使用 maltpoltlib 对带有轮廓的 pcolormesh 进行动画处理

Python if 语句 : False vs. 0.0

Python 在子列表中查找列表长度

python - 我发现自己挥舞着列表理解锤