Finding values ​​in a nested tuple

Say I have:

t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) 

And I need to check if the value is in the first bit of the nested tuple (i.e. the least significant bits). How can i do this? The recorded values ​​do not matter, I want to search for a string only in lowercase.

 if 'fish' in t: print "Fish in t." 

Does not work.

Is there a good way to do this without doing a for loop with if statements?

+4
source share
4 answers

Tuple elements can be extracted by specifying the index: ('a', 'b')[0] == 'a' . You can use the list description to iterate over all the elements of some iterable. A tuple can also be iterable. Finally, any() tells whether any element in the given iterable True matches. Putting it all together:

 >>> t = ( ... ('dog', 'Dog'), ... ('cat', 'Cat'), ... ('fish', 'Fish'), ... ) >>> def contains(w, t): ... return any(w == e[0] for e in t) ... >>> contains('fish', t) True >>> contains('dish', t) False 
+8
source

Try:

 any('fish' == tup[0] for tup in t) 

EDIT: Stefan is right; fixed "fish" == tup [0]. Also see His fuller answer.

+4
source

You can do something like this:

 if 'fish' in (item[0] for item in t): print "Fish in t." 

or that:

 if any(item[0] == 'fish' for item in t): print "Fish in t." 

If you don't need order, but want to keep the connection between 'dog' and 'dog' , you can use a dictionary instead:

 t = { 'dog': 'Dog', 'cat': 'Cat', 'fish': 'Fish', } if 'fish' in t: print "Fish in t." 
+2
source

If you have iterable key-value pairs, for example:

 t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) 

You can "translate" it into the dictionary using the dict () constructor, then use the in keyword.

 if 'fish' in dict(t): print 'fish is in t' 

This is very similar to the answer.

+2
source

All Articles