Testing a value in a tuple set

Suppose we have the following set: Sand the value v:

S = {(0,1),(2,3),(4,5)}
v = 3

I want to check if the vsecond element is any of the pairs within the set. My current approach:

for _, y in S:
    if y == v:
        return True
return False

I don’t really like this, because I have to add it to a separate function, and something tells me that maybe this is the best way to do this. Can anyone shed some light?

+3
source share
3 answers

The function is anydesigned for this:

any( y == v for (_, y) in S )

If you have a large set that does not change often, you can program the y values ​​onto the set.

yy = set( y for (_, y) in S )
v in yy

, , yy S, .

+6

O (1), . , .

S = {(0,1), (2,3), (4,5)}
T = {x[1] for x in S}

v = 3
if v in T:
    # do something
+2

Trivial answer any(see Marcelo's answer).

Alternative zip.

>>> zip(*S)
[(4, 0, 2), (5, 1, 3)]
>>> v in zip(*S)[1]
True
+1
source

All Articles