简体   繁体   English

如何根据列表索引过滤glom中的列表?

[英]How do I filter a list in glom based on list index?

I want to be able to filter out just 1, or perhaps all list items less than a certain index with glom, but the filter snippets in the snippet section of the glom documentation doesn't show me how to do that. 我希望能够过滤出1个,或者可能是所有列表项都少于某个索引的glom,但glom文档的片段部分中的过滤器片段并没有告诉我如何做到这一点。

Example (keep just the 2 first items in a list): 示例(仅保留列表中的2个第一项):

target = [5, 7, 9]
some_glom_spec = "???"

out = glom(target, some_glom_spec)

assert out == [5, 7]

Good question! 好问题! The approach you've got in your answer works, and you're on the right path with enumerate (that's the Pythonic way to iterate with index), but it could be more glom-y (and more efficient!). 你在答案中得到的方法是有效的,并且你在使用enumerate的正确路径上(这是用索引迭代的Pythonic方法),但它可能更加明显(并且效率更高!)。 Here's how I do it: 我是这样做的:

from glom import glom, STOP

target = [1, 3, 5, 7, 9]
spec = (enumerate, [lambda item: item[1] if item[0] < 2 else STOP])
glom(target, spec)
# [1, 3]

The third invocation of the lambda will return glom's STOP and glom will stop iterating on the list. lambda的第三次调用将返回glom的STOP并且glom将停止在列表上进行迭代。

You can read more about STOP (the glom singleton equivalent to break ), and its partner SKIP (the equivalent of continue ) in the glom API docs here . 您可以在此处的glom API文档中阅读有关STOP (相当于break的glom singleton)及其合作伙伴SKIP (相当于continue的更多信息

The only way I've found to do this so far is by enumerating the incoming target, converting to a list, and then have a lambda like in this snippet : 到目前为止,我发现这样做的唯一方法是枚举传入的目标,转换为列表,然后在这个片段中有一个lambda:

target = [5, 7, 9]
some_glom_spec = (enumerate, list, (lambda t: [i[1] for i in t if i[0] < 2]))

out = glom(target, some_glom_spec)

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

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