Le dim. 3 oct. 2021 à 16:21, firstname.lastname@example.org a écrit :
Date: Mon, 4 Oct 2021 01:03:34 +1100 From: Steven D'Aprano email@example.com Subject: [Python-ideas] Re: Feature request enumerate_with_rest or enumerate with skip or filter callback To: firstname.lastname@example.org Message-ID: 20211003140333.GR16229@ando.pearwood.info Content-Type: text/plain; charset=us-ascii
It is not clear to me what you mean by "filter by indices".
On Sat, Oct 02, 2021 at 10:25:05PM +0200, Laurent Lyaudet wrote:
The idea is to filter a list by indices :
Do you mean this?
No problem, I'll give more links next time :)
If that is what you want, it is easy to get access to the index. We can just do:
That's exactly what I proposed. Except for the fact that I incorrectly permuted the two arguments of filter. I quote my second email : Le sam. 2 oct. 2021 à 22:35, email@example.com a écrit :
Date: Sat, 2 Oct 2021 22:25:05 +0200 From: Laurent Lyaudet firstname.lastname@example.org ... Currently, the following solution is available : filter(enumerate(my_list), lambda x: x != i) But it is slightly ugly and unefficient to have two function calls for such a simple task I think.
I feel uncomfortable because it is often the case that I write explicitly something, and I get an answer as if the person answered without reading all my email or reading another version.
If you want something else, I'm afraid you will have to explain in more detail what you want, sorry.
Again for my second email, I would like one of these 3 options.
What would be your prefered way of doing this ? enumerate(my_list, filter_callback=(lambda x: x != i)) filter_by_index(my_list, lambda x: x != i) # à la JS filter(my_list, lambda _, x: x != i)
filter_by_index(lambda x: x != i, my_list) could be defined as follow (I permuted args to have similar order to python's filter()): def filter_by_index(function, my_list): for i, item in enumerate(my_list) if function(i): yield item like filter is just (without the case function=None) filter(function, my_list): for i, item in enumerate(my_list) if function(item): yield item The problem is not that it is hard to code in Python. The problem is that it is a basic building block for an iterators tools library like itertools.
enumerate(my_list, filter_callback=(lambda x: x != i)) could be defined in a similar way but there are two variants. It just needs to return one of the two indices of the item: - either the index of the item in the original sequence, - or the index of the item in the filtered sequence (new counter). For my use case, I do not need the index so I have no argument in favor of either one of the two indices.
# à la JS filter(my_list, lambda _, x: x != i)
You provided the link from MDN and an helper function for that. The lambda takes 2 or 3 parameters: item, index, array/list/sequence and returns true for item that must be output. I see nothing more to say.
Best regards, Laurent Lyaudet