Finding a 2 dimensional set / list in Python

I want to search tuple of tuplesfor a specific row and return the index of the parent tuple. I seem to often come across variations of this kind of search.

What is the most pythonic way to do this?

i.e:

derp = (('Cat','Pet'),('Dog','Pet'),('Spock','Vulcan'))
i = None
for index, item in enumerate(derp):
    if item[0] == 'Spock':
         i = index
         break
>>>print i
2

I could generalize this to a small utility function that takes iterability, an index (in the example I am hard-coded 0), and a search value. This does the trick, but I have an opinion that for him, probably, a single-line interface;)

i.e:

def pluck(iterable, key, value):
    for index, item in enumerate(iterable):
        if item[key] == value:
             return index
    return None
+3
source share
5 answers

This is a trick, but I have this opinion that perhaps there is a one-liner for him;)

A single-line font is probably not a pythonic way:

The method you used looks great.

Edit:

:

return next( (i for i,(k,v) in enumerate(items) if k=='Spock'),None)

next ( None) .

+4

:

dict(derp)[<key_name>]

.

dict(derp)['Cat']

"Pet"

+4

If you often look for the same tuple, you can build a dict.

lookup_table = dict((key, i) for i, (key, unused) in enumerate(derp))

print lookup_table['Spock']
--> 2
+1
source

Another way to get it in one line:

[d[0] for d in derp].index("Spock")

I am not sure if the iterator evaluates all the values โ€‹โ€‹before calling the index, and therefore they are inefficient.

0
source

Lambda is fun!

return reduce(
    lambda x,(i,(a,b)): i,
    filter(
        lambda (i,(a,b)): a == "Spock",
        enumerate(depr)
    ),
    None
)
-1
source

Source: https://habr.com/ru/post/1731522/


All Articles