Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

glom

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]
like image 390
Ulrik Avatar asked Aug 16 '19 09:08

Ulrik


2 Answers

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.

like image 88
Mahmoud Hashemi Avatar answered Nov 04 '22 02:11

Mahmoud Hashemi


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)
like image 23
Ulrik Avatar answered Nov 04 '22 03:11

Ulrik