简体   繁体   中英

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.

Example (keep just the 2 first items in a list):

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!). 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.

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 .

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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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