Conditionally listing elements in python

I would like to list those elements in an iterable that satisfy a certain condition. I tried something like

[(i,j) for i,j in enumerate(range(10)) if (3 < j) and (j < 8)] 

(which tries to list numbers from 4 to 7 just for example). From this I get the result

 [(4, 4), (5, 5), (6, 6), (7, 7)] 

I would like to receive

 [(0, 4), (1, 5), (2, 6), (3, 7)] 

Is there a pythonic way to achieve the desired result?

Please note that in the real problem I'm working on, I don’t know in advance how many elements satisfy the condition.

+6
source share
3 answers

Repeat the listing so that the indices start at 0.

 enumerate(j for j in range(10) if (3 < j) and (j < 8)) 

If you need a list, rather than listing an object, just wrap it all in list()

+13
source

You can filter in the generator, and then enumerate on the result of this expression.

 >>> [(index,value) for index,value in enumerate(j for j in range(10) if (3 < j) and (j < 8))] [(0, 4), (1, 5), (2, 6), (3, 7)] 

Or, equivalently, enumerate will give tuples (index, value) already so you can use

 >>> list(enumerate(j for j in range(10) if (3 < j) and (j < 8))) [(0, 4), (1, 5), (2, 6), (3, 7)] 
+4
source

Why you are wrong: you get the result, then filter it.

[(i,j) for i,j in enumerate(range(10))] will get [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)] , then you use if (3 < j) and (j < 8) (j - second element in the tuple), so the result will be [(4, 4), (5, 5), (6, 6), (7, 7)]

What you need to do: first filter the sequence passed to range() .

this means: for example, you want to list numbers from 4 to 7, so filter first

 >>> [j for j in range(10) if 3 < j < 8] [4, 5, 6, 7] 

then you pass it to enumerate :

 >>> list(enumerate([4, 5, 6, 7])) [(0, 4), (1, 5), (2, 6), (3, 7)] 

therefore the solution should be:

 >>> list(enumerate(i for in range(10) if 3 < i < 8)) [(0, 4), (1, 5), (2, 6), (3, 7)] 

In a word, just remember to do the first filtering .

+2
source

Source: https://habr.com/ru/post/987671/


All Articles