Pergunta

I have a namedtuple, that contains several namedtuples within it.

Each of the inner tuples essentially has a unique 'id', along with other useful information. I know the ID of the tuple I want to access, and Im wondering if there's an easy way to 'index' the namedtuple to extract the exact element I want without doing something like:

for inner_tuple in outer_tuple:
    if inner_tuple.id == desired_id:
        found tuple = inner_tuple
        break
Foi útil?

Solução

You can use a generator expression with next() to find the first match, or None if nothing matched. This still requires a loop:

found = next((tup for tup in outer_tuple if tup.id == desired_id), None)

The alternative is to use a dictionary keyed on id instead.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top