Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Matching

a = ('one', 'two')
b = ('ten', 'ten')

z = [('four', 'five', 'six'), ('one', 'two', 'twenty')]

I'm trying 1) see if the first two elements in my tuples (a, or b, for example), match up with the first two elements in my list of tuples (z). 2)if there is a match, I want to return the third element of the tuple

so i want to get

myFunc(a,z) -> 'twenty'
myFunc(b,z) -> None
like image 476
appleLover Avatar asked Feb 14 '23 10:02

appleLover


1 Answers

Using generator expression, and next:

>>> a = ('one', 'two')
>>> b = ('ten', 'ten')
>>> z = [('four', 'five', 'six'), ('one', 'two', 'twenty')]
>>> next((x[2] for x in z if x[:2] == a), None)
'twenty'
>>> next((x[2] for x in z if x[:2] == b), None)
>>>
like image 174
falsetru Avatar answered Feb 17 '23 03:02

falsetru