0
db = [('cat',15,22),('dog',28,30),('human',27,80)]

Now I want to create search for 'dog' so my returned value will be db[1]. I can't still figure it out (I know I would use sth like for item in db: if 'dog' in item[:] but don't know how to put it together really.

Please help?

user3056783
  • 2,265
  • 1
  • 29
  • 55

4 Answers4

3
items = [i for i in db if 'dog' in i]
items[0] if items else None
# ('dog', 28, 30)
Matt
  • 17,290
  • 7
  • 57
  • 71
  • You don't need to convert the tuple into a list to use `in`. `[i for i in db if 'dog' in i]` would work as well. – Utaal Mar 24 '14 at 08:40
  • Also, @user3056783 wants his returned value to be `db[1]` so this should be `[i for i in db if 'do' in i][0]`; this of course would blow up with an `IndexError: list index out of range` if 'dog' was not found (as the list you constructed would be empty). – Utaal Mar 24 '14 at 08:49
  • 1
    I added the code to safely check for an empty result. – Matt Mar 24 '14 at 08:57
  • Yes I like this one and sort of understand it. If i were to look more into it, what is this kind of coding called: `[i for i in db if 'dog' in i]` ? Just so I know what to search for. – user3056783 Mar 24 '14 at 10:40
  • @user3056783 it's called a "list comprehension"; there's also a similarly looking syntax for generators (I'd recommend reading about those as well as they're pretty ubiquitous in python): `(i for i in db if 'dog' in i)` (this is what I'm using in my answer) – Utaal Mar 24 '14 at 10:53
2

If you're looking for the first item that matches (as suggested by you saying that your returned value should be db[1]) then you can use

next((x for x in db if x[0] == 'dog'), None)

In case 'dog' may be in any element of the tuple - so that (28, 'dog', 30) would also be matched - I'd go with

next((x for x in db if 'dog' in x), None)

See the answers to find first element in a sequence that matches a predicate for how this works.

Community
  • 1
  • 1
Utaal
  • 8,484
  • 4
  • 28
  • 37
1

You can use filter:

filter(lambda x:'dog' in x, db)

Output:

[('dog', 28, 30)]
venpa
  • 4,268
  • 21
  • 23
1

You mean this?

f = lambda db,x: [_t for _t in db if _t[0]==x][0]

Output:

>>> f(db,'dog')
('dog', 28, 30)
AuBee
  • 86
  • 9