4
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
appleLover
  • 14,835
  • 9
  • 33
  • 50
  • What do you want to have when more than one element matches? – BartoszKP Dec 11 '13 at 13:43
  • Well I am trying to match a, b, or whatever to a table I am loading from a database. All entries in DB should be unique so there should just be one match. I think I can safely grab the first match found and stop searching immediately to make the program run faster. – appleLover Dec 11 '13 at 13:46
  • 2
    All right. Then indeed falsetru's answer seems better. – BartoszKP Dec 11 '13 at 13:49

2 Answers2

5

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)
>>>
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    how come in your implementation of next() it seems to iterate through the entire generator, but based on the example here, http://stackoverflow.com/questions/1733004/python-next-function, using next() just processes ONE element in a generator expression? – appleLover Dec 11 '13 at 13:47
  • 1
    @appleLover, The generator yields only if the item match. And `next` fetch one item from that generator. – falsetru Dec 11 '13 at 13:56
  • 1
    @BartoszKP, `next` is applied to the generator. The generator is not wrapped inside a sequence. It is the first argument to the `next` function. – falsetru Dec 11 '13 at 13:59
  • 2
    @appleLover: the generator expression here only produces strings for matching tuples, one at a time. `next()` is not applied directly to `z`, it is applied to a filtered 'view' of `z`, so to speak. – Martijn Pieters Dec 11 '13 at 14:01
  • Sorry for causing confusion and thanks for explaining. – BartoszKP Dec 11 '13 at 14:17
3

Simplest solution seems to be:

def myFunc(t, tList):
    return [r[-1] for r in tList if r[:2] == t] or None
BartoszKP
  • 34,786
  • 15
  • 102
  • 130