Python - iterating over a subset of a list of tuples

Say I have a list of tuples as shown below

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

I would like to iterate over the elements where the 2nd element in the tuple is 1?

I can do this using the if condition in the loop, but I was hoping this would be a good pythonic way to do this?

thanks

+6
source share
7 answers

You can use list comprehension:

 [ x for x in l if x[1] == 1 ] 

You can also iterate over tuples using the generator syntax:

 for tup in ( x for x in l if x[1] == 1 ): ... 
+6
source

What about

 ones = [(x, y) for x, y in l if y == 1] 

or

 ones = filter(lambda x: x[1] == 1, l) 
+3
source

Just use if . It is clear and simple.

 for x, y in tuples: if y == 1: do_whatever_with(x) 
+3
source

Create a generator above it:

 has_1 = (tup for tup in l if l[1] == 1) for item in has_1: pass 
+2
source
 for e in filter(l, lambda x: x[1] == 1): print e 
+2
source

Try this using a list of concepts - this is a pythonic way to solve the problem:

 lst = [(4,1), (5,1), (3,2), (7,1), (6,0)] [(x, y) for x, y in lst if y == 1] => [(4, 1), (5, 1), (7, 1)] 

Notice how we use the tuple x, y unpacking to get each of the elements in the pair and how the condition if y == 1 filters only that element with a value of 1 in the second element of the pair. After that, you can do whatever you want with the elements found, in particular, I restore the original pair in this part on the left: (x, y)

+1
source

Since you want iteration, itertools.ifilter is a good solution:

 from itertools import ifilter iter = ifilter(lambda x: x[1] == 1, l) for item in iter: pass 
+1
source

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


All Articles