items = [i for i in db if 'dog' in i]
items[0] if items else None
# ('dog', 28, 30)
Search in python tuple list
-
20-06-2023 - |
문제
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?
해결책
다른 팁
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.
You can use filter:
filter(lambda x:'dog' in x, db)
Output:
[('dog', 28, 30)]
You mean this?
f = lambda db,x: [_t for _t in db if _t[0]==x][0]
Output:
>>> f(db,'dog')
('dog', 28, 30)
제휴하지 않습니다 StackOverflow